单例模式
<?php
/**
* Single.php
* Created on 2020/8/5 7:56 下午
* Created by chenzhuo
* description :
*/
class Single
{
static public $instance = null;
private function __construct()
{
echo "new-class </br>";
}
public static function getInstance() {
if(!self::$instance){
self::$instance = new self();
}
return self::$instance;
}
public function getCalm() {
return "calm";
}
}
调用
$calm = \Single::getInstance()->getCalm();
// \Single::getInstance()->getCalm();
// \Single::getInstance()->getCalm();
// \Single::getInstance()->getCalm();
// \Single::getInstance()->getCalm();
// \Single::getInstance()->getCalm();
echo $calm;
注册树模式
1、注册树模式通过将注册实例注册到一棵全局的对象树上
2、需要的时候从对象树上采摘下来使用
<?php
/**
* ClamRegister.php
* Created on 2020/8/5 8:12 下午
* Created by chenzhuo
* description :
*/
class ClamRegister
{
/**
* 注册树池子
* @var null
*/
protected static $objects = null;
/**
* Notes:将对象挂到对象树上
* @param $key
* @param $object
* User: chenzhuo
* Date: 2020/8/5 8:15 下午
*/
public static function set($key, $object) {
self::$objects[$key] = $object;
}
/**
* Notes: 从树上获取对象, 如果没有 注册
* @param $key
* @return mixed
* User: chenzhuo
* Date: 2020/8/5 8:16 下午
*/
public static function get($key) {
if(!isset(self::$objects[$key])){
self::$objects[$key] = new $key;
}
return self::$objects[$key];
}
/**
* Notes: 注销
* @param $key
* User: chenzhuo
* Date: 2020/8/5 8:18 下午
*/
public static function _unset($key)
{
unset(self::$objects[$key]);
}
}
调用
<?php
/**
* A.php
* Created on 2020/8/5 8:21 下午
* Created by chenzhuo
* description :
*/
class A {
public function calm() {
return "calmA";
}
}
$calm = \ClamRegister::get("A")->calm();
var_dump($calm);