Correction status:Uncorrected
Teacher's comments:
单例模式,工厂模式用于创建实例,注册树模式用来管理创建的实例
单例模式 Singleton.php
<?php /** * */ class Singleton { private static $instance=null; private $setting=[]; private function __construct() { } private function __clone() { } public static function getInstance(){ if (self::$instance == null) { self::$instance=new self(); } return self::$instance; } public function set($index,$value){ $this->setting[$index]=$value; } public function get($index){ return $this->setting[$index]; } } //$obj1,$obj2 同一个对象 $obj1=Singleton::getInstance(); $obj2=Singleton::getInstance(); var_dump($obj1,$obj2); $obj1->set('pass','root'); echo $obj1->get('pass');
点击 "运行实例" 按钮查看在线实例
工厂模式 Factory.php
<?php /** * */ class Factory { public static function create($type,$price){ switch ($type){ case 'apple': return new Apple($price); break; case 'xiaomi': return new Xiaomi($price); break; } } } class Apple { private $price; public function __construct($price) { $this->price=$price; } public function price(){ return $this->price; } } class Xiaomi { private $price; public function __construct($price) { $this->price=$price; } public function price(){ return $this->price; } } $apple=Factory::create('apple',5000); echo $apple->price(); echo '<hr>'; $xiaomi=Factory::create('xiaomi',3000); echo $xiaomi->price();
点击 "运行实例" 按钮查看在线实例
注册树 Registry.php
<?php /** * */ class Demo1{} class Demo2{} class Demo3{} class Registry { public static $objs=[]; public static function set($index,$obj){ self::$objs[$index]=$obj; } public static function get($index){ return self::$objs[$index]; } public static function del($index){ unset(self::$objs[$index]); } } //类实现注册到注册树 Registry::set('demo1',new Demo1()); Registry::set('demo2',new Demo2()); Registry::set('demo3',new Demo3()); var_dump(Registry::$objs); echo '<hr>'; echo '<pre>'; print_r(Registry::$objs); echo '<hr>'; var_dump(Registry::get('demo1')); //del echo '<hr>'; Registry::del('demo1'); var_dump(Registry::get('demo1'));
点击 "运行实例" 按钮查看在线实例