开发者

Design Pattern for a Class to be Instantiated Once

What object-oriented design开发者_如何学Python pattern would you use to implement a class that can only be instantiated once (in PHP)?


You really need to think about your specific situation. Here are some patterns to keep in mind when deciding what works in you need. Often, the Singleton can be used effectively with either a Service Locator or a Factory.

Singleton

Service Locator

Factories


That's a Singleton.


singleton but i always ,always think twice before making use of it.


You're looking for a Singleton.

Check out this tutorial about implementing a singleton with php (as per your tag).


Here's an Singleton pattern example in PHP. Technically, it allows up to two instances to be created, but croaks in the constructor when an instance already exists:

<?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);  

You'll also want to take a look at __clone depending on how tightly you need to control the instance invocations.


You're looking for the Singleton pattern.


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();


Ummmm.... singleton

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜