1. 程式人生 > >PHP的單例模式 ,工廠模式,註冊模式的例子

PHP的單例模式 ,工廠模式,註冊模式的例子

<?php
/**
 * Created by PhpStorm.
 * User:
 * Date: 2018/12/6
 * Time: 14:11
 */
class Site
{
    //屬性
    public $siteName;
    //本類的靜態例項
    protected static $instance = null;
    //禁用構造器
    private function __construct($siteName){
        $this->siteName = $siteName;
    }
    //獲取本類唯一例項
    public static function getInstance($siteName){
        if(!self::$instance instanceof self){
            self::$instance = new self($siteName);
        }
        return self::$instance;
    }
}

//使用工廠模式生成類的單一例項
class Factory
{
    //建立指定類的例項
    public static function create()
    {
        return Site::getInstance('PHP');
    }
}

//物件註冊樹
/**
 * Class Register
 * 1. 註冊:set(),把物件掛到樹上
 * 2. 獲取:get(),把物件取來用
 * 3. 登出:unset():把物件吃掉
 */
class Register
{
    //建立物件池:陣列
    protected static $objects = [];
    //生成物件並上樹
    public static function set($alias,$object){
        self::$objects[$alias] = $object;
    }
    //從樹上取出物件
    public static function get($alias){
        return self::$objects[$alias];
    }
    //登出樹上物件
    public static function _unset($alias){
        unset(self::$objects[$alias]) ;
    }
}

//將Site類的例項加入物件資源池
Register::set('site',Factory::create());
//獲得物件
$obj = Register::get('site');
var_dump($obj);
var_dump($obj->siteName);