要实例化的类的设计模式

时间:2010-06-23 19:15:16

标签: php oop design-patterns

您将使用哪种面向对象的设计模式来实现一个只能实例化一次的类(在PHP中)?

7 个答案:

答案 0 :(得分:3)

你真的需要考虑你的具体情况。在决定您需要什么时,请记住以下几种模式。通常,Singleton可以有效地与服务定位器或工厂一起使用。

Singleton

Service Locator

Factories

答案 1 :(得分:2)

那是Singleton

答案 2 :(得分:2)

您正在寻找Singleton

查看this tutorial关于使用php实现单例(根据您的标记)。

答案 3 :(得分:2)

单身,但我总是在使用它之前总是三思而行。

答案 4 :(得分:1)

这是PHP中的Singleton模式示例。从技术上讲,它最多允许创建两个实例,但是当实例已经存在时,构造函数中会出现错误:

<?php

class Singleton {

 static protected $_singleton = null;

 function __construct() {
  if (!is_null(self::$_singleton))
   throw new Exception("Singleton can be instantiated only once!");
  self::$_singleton= $this;  
 }

 static public function get() {
   if (is_null(self::$_singleton))
    new Singleton();
   return self::$_singleton;
 }

}

$s = new Singleton();
var_dump($s);
$s2 = Singleton::get();
var_dump($s2);  // $s and $s2 are the same instance.
$s3 = new Singleton();  // exception thrown
var_dump($s3);  

您还需要查看__clone,具体取决于您控制实例调用的紧密程度。

答案 5 :(得分:1)

您正在寻找Singleton模式。


class Foo {

    private static $instance = null;

    private function __construct() { }

    public static function instance() {

        if(is_null(self::$instance))
            self::$instance = new Foo;

        return self::$instance;
    }

    public function bar() {
        ...
    }
}

$foo = Foo::instance();
$foo->bar();

答案 6 :(得分:0)

嗯......单身人士