单例模式

design patern singleton

本文记录下单例模式的几种应用场景,主要是以代码的方式呈现出来。

基本形态的单例

<?php

class Singleton
{
    private static $_instance;
    private function __construct(){}

    public function __clone(){
        trigger_error("clone method isn't callable.", E_USER_ERROR);
    }
    public static function getInstance(){
        if(!self::$_instance){
            self::$_instance = new self();
        }
        return self::$_instance;
    }
}

单例与继承的结合

abstract class Web
{
    private static $_instance = [];

    public static function getInstance()
    {
        $class = get_called_class();
        if (!array_key_exists($class, self::$_instance) || !self::$_instance[$class])
        {
            self::$_instance[$class] = new static();
        }
        return self::$_instance[$class];
    }
    public function __clone(){
        trigger_error("clone method is not allowed.", E_USER_ERROR);
    }
}
class Pc extends Web
{
}
class H5 extends Web
{
}
var_dump(Pc::getInstance());
var_dump(H5::getInstance());

抽象的单例 – 一个通用的单例类

<?php
abstract class Singleton
{
    private static $_instances = array();

    protected function __construct(){}

    final public function __clone()
    {
        trigger_error("clone method isn't callable.", E_USER_ERROR);
    }

    final public static function getInstance()
    {
        $c = get_called_class();
        if(!isset(self::$_instances[$c])) {
            self::$_instances[$c] = new $c;
        }
        return self::$_instances[$c];
    }
}

class Cache Extends Singleton
{
}

class Db extends Singleton
{
}
$cache = Cache::getInstance();
var_dump($cache);
$db = Db::getInstance();
var_dump($db);
单例模式
Tags:             

发表评论

电子邮件地址不会被公开。 必填项已用*标注