工厂模式
, factory method or class generates objects instead of new<code class="language-php" hljs=""> class Factory{ static function getDatabase(){ return new Mysql($host, $user, $pass); } } #使用 Factory::getDatabase(); </code>
单例模式
, so that an object of a certain class can only create one 1. There is a private static object variable that specifically stores objects of this class. 2. There is a static method to create objects. 3. There is a private constructor to prevent external new objects. 4. There is a clone method to prevent clone from returning false.
Reference article Singleton Pattern
<code class="language-php" hljs="">class Database { //单一对象属性 private static $instance; //定义一些全局变量需要存放属性 private $props = array(); //私有的构造方法 private function __construct(){ echo 'into construct! 该类不允许外部创建对象 '; } //返回单一实例 public static function getInstance () { //判断是否已经有了实例化的对象 if(empty(self::$instance)) { //可以被override (动态解析) self::$instance = new static(); //不可以被override (静态解析) //self::$instance = new self(); } return self::$instance; } public function __clone(){ return '该类禁止clone'; } //设置属性 public function setProperty ( $key, $value) { $this->props[$key] = $value; } //获取属性 public function getPeoperty ( $key ) { return $this->props[$key]; } } //使用 $dbObj = Database::getInstance(); $dbObj->setProperty('root_path','/www'); $dbObj->setProperty('tmp_path','/tmp'); //接下来删除该单例对象,如果还能获取到刚刚添加的属性,说明使用的是同一个对象 unset($dbObj); $dbObj = Database::getInstance(); echo $dbObj->getPeoperty('root_path'); echo $dbObj->getPeoperty('tmp_path'); </code>
1. Register and add aliases to the same object that needs to be used multiple times, and call and use it uniformly. (For example, when a customer buys a machine, he must go to an institution recognized by the factory to buy it, instead of everyone going to the factory to buy it.) 2. Think about it next time When using an object, you don’t need to use a factory or singleton mode. You can just get it directly from the register
<code class="language-php" hljs=""> class Register (){ protected static $objects; function set($alias, $object){ self::$objects[$alias] = $objects; } function get($alias){ return self::$objects[$alias]; } function _unset($alias){ unset(self::$objects[$alias]); } }</code>
<code class="language-php" hljs=""> class Factory{ static function getDatabase(){ //单例模式获取数据对象 $dbObj = Database::getInstance(); //注册到全局树上 Register::set('db1', $dbObj); } } #使用 //第一次主文件里面 Factory::getDatabase(); //以后使用数据库对象直接访问 Register::get('db1');</code>