2013-12-22 62 views
1

請告訴我請示例php中的多態sigleton。需要多態單例在php

谷歌發現很少提到這件事,都用C這是不是很清楚,我

+0

http://phpadvocate.com/blog/2011/04/php-using-a-singleton-pattern-with-oop/ –

回答

0

在這裏你去:

/** 
* Base class for Polymorphic Singleton. 
*/ 
class Polymorphic_Singleton { 

    /** 
    * @var Polymorphic_Singleton 
    */ 
    private static $__instance = null; 
    private static $__instance_class_name = ""; 


    /** 
    * Gets an instance of Polymorphic_Singleton/ 
    * 
    * Uses a Polymorphic Singleton design pattern. Maybe an anti-pattern. Discuss amongst yourselves. 
    * 
    * Can be called by a subclass, and will deliver an instance of that subclass, which most Singletons don't do. 
    * You gotta love PHP. 
    * 
    * @return Polymorphic_Singleton 
    */ 
    final public static function get_instance(){ 
     if (! isset(self::$__instance)){ 
      self::$__instance_class_name = get_called_class(); 
      self::$__instance = new self::$__instance_class_name(); // call the constructor of the subclass 
     } 

     return self::$__instance; 
    } 

    /** 
    * Don't ever call this directly. Always use Polymorphic_Singleton ::get_instance() 
    * 
    * @throws Exception if called directly 
    */ 
    public function __construct(){ 
     if (! self::$__instance){ 
      // do constructor stuff here... 
     } else { 
      throw new Exception("Use 'Polymorphic_Singleton ::get_instance()' to get a reference to this class.", 100); 
     } 
    } 
} 
0

我不清楚地瞭解你所說的「多態單」是什麼意思。 Singleton模式本身已經在很多地方已經說明那裏,例如:

http://en.wikipedia.org/wiki/Singleton_pattern

在PHP中,你可以使用這個簡單的代碼實現Singleton模式:

<?php 

class Something 
{ 
    private static $instance; 

    private function __construct() {} 
    private function __clone() {} 

    public static function getInstance() 
    { 
     if (null === self::$instance) { 
      self::$instance = new self(); 
     } 

     return self::$instance; 
    } 
} 

// how to use 
$instance1 = Something::getInstance(); 
$instance2 = Something::getInstance(); 
var_dump($instance1 === $instance2); // returns true proving that getInstance returns identical instance 
+0

我知道單身模式,id喜歡瞭解自己什麼是多態單身意思,這就是爲什麼問這裏的問題:) 可能是意味着通過單身模式的服務經理類 – Eugene