Home >Backend Development >PHP Tutorial >PHP design patterns: factory mode, singleton mode and registration mode

PHP design patterns: factory mode, singleton mode and registration mode

高洛峰
高洛峰Original
2016-12-17 11:00:131230browse

The three most common design patterns in all object-oriented are: factory mode, singleton mode, registration (container) mode

Factory mode, factory method or class generates objects, instead of directly new in the code

single case mode, allowing only one object of a certain class to be created

Registration mode, global sharing and exchange objects

Factory mode factory.php

<?php
class Database{
    public function __construct()
    {
        return "Database\n";
    } 
 
}
//工厂类
class Factory{
    public static function createDatabase()
    {
        $db = new Database();
        return $db;
    }
}
 
$db = Factory::createDatabase();
$db1 = Factory::createDatabase();
$db2 = Factory::createDatabase();
 
var_dump($db, $db1, $db2);
#object(Database)#1 (0) {
#}
#object(Database)#2 (0) {
#}
#object(Database)#3 (0) {
#}

Singleton mode singleton.php

<?php
//单例模式
class Database{
    protected static $db;
    //构造方法私有,防止在外层直接new
    private function __construct(){
        //code
    }
 
    static function getInstance(){
        if (self::$db) {
            return self::$db;
        }else{
            self::$db = new self();
            return self::$db;
        }
    }
}
 
$db = Database::getInstance();
$db1 = Database::getInstance();
$db2 = Database::getInstance();
 
var_dump($db, $db1, $db2);
#object(Database)#1 (0) {
#}
#object(Database)#1 (0) {
#}
#object(Database)#1 (0) {
#}

Factory mode and singleton are used together

<?php
class Database{
    protected static $db;
    private function __construct(){
        
    }
 
    static function getInstance(){
        if (self::$db) {
            return self::$db;
        }else{
            self::$db = new self();
            return self::$db;
        }
    }
}
class Factory{
    public static function createDatabase(){
        return Database::getInstance();
    }
}
 
var_dump(Factory::createDatabase());

Register class register.php

<?php
//注册器模式
class Register
{
    protected static $objects;
 
    static function set($alias, $object){
        self::$objects[$alias] = $object;
    }
    static function get($name){
        return self::$objects[$name];
    }
    function _unset($alias){
        unset(self::$objects[$alias]);
    }
}
 
Register::set(&#39;db1&#39;, $db);
Register::get(&#39;db1&#39;);



For more articles related to PHP design patterns: factory mode, singleton mode and registration mode, please pay attention to PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn