php 单列模式 - 点滴记忆*记忆点滴
收藏本站

php 单列模式

单列模式是设计模式中常见的模式之一。

php 中单列模式实现方式有以下两种:

方式一、

<?php
class Example
{
    // 保存类实例在此属性中
    private static $instance;
    
       // 构造方法声明为private,防止直接创建对象
    private function __construct() 
    {
        echo 'I am constructed';
    }

    // singleton 方法
    public static function singleton() 
    {
        if (!isset(self::$instance)) {
            $c = __CLASS__;
            self::$instance = new $c;
        }

        return self::$instance;
    }
    
    // Example类中的普通方法
    public function bark()
    {
        echo 'Woof!';
    }

    // 阻止用户复制对象实例
    public function __clone()
    {
        trigger_error('Clone is not allowed.', E_USER_ERROR);
    }

}

?>

方式二、

<?php
class Singleton {
  // 每个子类都必须定义这个变量
  protected static $_instance;

  // 获取单列方法
  final public static function instance() {
    // create the instance if we don't have one
    if (empty(static::$_instance)) {
      $class = get_called_class(); // php 5.3.0 及以上支持
      static::$_instance = new $class;
    }

    return static::$_instance;
  }

  // 定义为protected 只允许子类调用
  protected function __construct() { }

  // 不允许克隆
  final public function __clone() {
    throw new Exception('Cannot duplicate a singleton.');
  }
}

//要实现单列的子类
class Extension extends Singleton {
  // 必须定义该变量
  protected static $_instance;

  protected function __construct() { ... }

  public function foo() {
    echo 'foo\n';
  }
}

// example
$extension = Extension::instance();
$extension->foo(); // echo's 'foo\n' as expected
?>




    留下足迹