单例模式Singleton概述

单例模式属于建立型模式,它是设计模式中最简单的一种模式,固然它的使用也是无处不在的。
单例模式保证一个类仅有一个实例,并提供一个访问它的全局访问点。
当须要控制一个类的实例数量,且调用者能够从一个公共的众所周知的访问点访问时,咱们就能够考虑使用单例模式了。
咱们用 UML 来设计单例模式,固然在之后的设计模式的设计部分,咱们都将采用 UML 来描述咱们的设计,这样就更为形象化了。
从 UML 设计图中咱们能够看出,为了让一个类只有一个实例,它必须建立一个静态变量,而后咱们用一个公共静态的 Instance() 的方法来建立它,可是为了不这个类自身的构造函数能够建立对象,咱们将构造函数设置成 protected 或者 private,这样外部就只能经过 Instance() 的方法来建立一个静态的 Singleton 类。看来这样咱们达到了咱们的目的,接下来咱们看代码:
1 public class Singleton  {
2     private static Singleton instance;
3     protected Singleton()
4     public static Singleton Instance() {
5         if(instance != null) instance = new Singleton();
6         return instance;
7     }
8 }
由此看来,实现单例模式咱们能够作下列几步:
  1. 在类中建立一个静态变量,变量类型为当前类;
  2. 在类中建立一个公共的静态方法,让用户能够经过此方法建立此类的静态对象;
  3. 最后将构造函数设置为 protected 或者 private。

Program List:最简单的单例类

01 <?php
02 class Fruit
03 {
04     static private $_color;
05     private function __construct()
06     {
07     }
08       
09     static public function singleton() {
10         return isset(self::$_color) ? self::$_color : self::$_color = new self();
11     }
12 }
13 ?>

Program List:可扩展的单例类

一个可扩展的单例类看似不可能,但下面的程序很接近这种效果。
001       
002 <?php
003 class Test extends Fruit {
004   
005     public static function getInstance()
006     {
007         return Fruit::getSingleton(get_class());
008     }
009   
010 }
011 ?>
012   
013 <?php
014 class Fruit {
015   
016     /***********************
017      * HOW TO USE
018      
019      * Inherit(extend) from Singleton and add getter:
020      
021      *  //public getter for singleton instance
022      *     public static function getInstance(){
023      *        return Singleton::getSingleton(get_class());
024      *    }
025      
026      */
027       
028     private static $instanceMap = array();
029   
030     //protected getter for singleton instances
031     protected static function getSingleton($className)
032     {
033         if(!isset(self::$instanceMap[$className]))
034         {
035               
036             $object = new $className;
037             //Make sure this object inherit from Singleton
038             if($object instanceof Fruit)
039             {    
040                 self::$instanceMap[$className] = $object;
041             }
042             else
043             {
044                 throw SingletonException("Class '$className' do not inherit from Singleton!");
045             }
046         }
047         return self::$instanceMap[$className];
048     }    
049       
050     //protected constructor to prevent outside instantiation
051     protected function __construct(){
052     }
053       
054     //denie cloning of singleton objects
055     public final function __clone(){
056         trigger_error('It is impossible to clone singleton', E_USER_ERROR);
057     }    
058 }
059 ?>
060   
061 <?php
062 class Apple extends Fruit {
063       
064     protected $rndId;
065       
066     protected function __construct(){
067         $this->rndId = rand();
068     }    
069       
070     public function whatAmI(){
071         echo 'I am a Apple('.$this->rndId.')<br />';
072     }
073   
074     public static function getInstance(){
075         return Fruit::getSingleton(get_class());
076     }
077   
078 }
079   
080 class GreenApple extends Apple {
081   
082     public function whatAmI(){
083         echo 'I am a GreenApple('.$this->rndId.')<br />';
084     }
085       
086     public static function getInstance(){
087         return Fruit::getSingleton(get_class());
088     }
089   
090 }
091   
092 $apple1 = Apple::getInstance();
093 $apple2 = GreenApple::getInstance();
094   
095 $apple1->whatAmI();// should echo 'I am a A(some number)
096 $apple2->whatAmI();// should echo 'I am a B(some number)
097   
098 $apple1 = Apple::getInstance();
099 $apple2 = GreenApple::getInstance();
100   
101 $apple1->whatAmI();// should echo 'I am a A(same number as above)
102 $apple2->whatAmI();// should echo 'I am a B(same number as above)
103   
104 // $a = new A();// this should fail
105 // $b = new B();// this should fail
106   
107 ?>
程序运行结果:
1 I am a Apple(4462)
2 I am a GreenApple(8207)
3 I am a Apple(4462)
4 I am a GreenApple(8207)

Program List:单例类与其派生类

01     
02 <?php
03   
04 class Fruit
05 {
06   // Hold an instance of the class
07   private static $instance;
08    
09   // A private constructor; prevents direct creation of object
10   protected function __construct()
11   {
12       echo 'I am constructed';
13   }
14   // The singleton method
15   public static function singleton($classname = __CLASS__)
16   {
17       if (!isset(self::$instance)) {
18           self::$instance = new $classname;
19       }
20       return self::$instance;
21   }
22 }
23   
24 class Apple extends Fruit {
25    public static function singleton()
26    {
27        return parent::singleton(__CLASS__); // NOTE The singleton method MUST return an instance.
28    }
29    public function showColor()
30    {
31        echo 'My Color is Red.';
32    }
33 }
34   
35 $subclassInstance = Apple::singleton();
36 $subclassInstance->showColor();
37 ?>
程序运行结果:
1 I am constructed
2 My Color is Red.
相关文章
相关标签/搜索