注册树模式
注册树模式也叫注册模式或注册器模式
核心思想是将多个对象注册到一个全局或指定对象中,在代码中可以随时随地调用注册到全局对象中的对象,最终目的是实现全局共享和交换对象的功能
namespace common;
class Test{
pubcli function t()
{
echo 'hello word!';
}
}
namespace common;
class Register{
public static inti($class_list, $app)
{
foreach ($component as $item => $value) {
$app->$item = new $value();
}
return $app;
}
}
namespace common;
class Applicton{
public static $app = null;
public static function getInstance()
{
if (is_null(static::$self) && !(static::$self instanceof self)) {
static::$self = new static();
}
return static::$self;
}
}
demo: 将对象注册到$app对象中
use common\Appliction;
use common\Register;
$app = Appliction::getInstance();
$class_list = [
'test' => 'common\Test',
];
$app = Register::init($class_list, $app);
//使用
ehco $app->test->t();
//输出 hello word!
demo: 将对象注册到全局Application静态属性中
use common\Appliction;
use common\Register;
$class_list = [
'test' => 'common\Test',
];
Appliction::$app = Register::init($class, Appliction::$app);
//使用
echo Appliction::$app->test->t();
//输出 hello word!
本文深入探讨了注册树模式,一种允许全局对象注册和共享多个对象的设计模式。通过具体实例展示了如何在PHP中实现该模式,包括对象的注册、初始化及调用过程。
979

被折叠的 条评论
为什么被折叠?



