Let's talk about Singleton in PHP Singleton mode.

Source: Internet
Author: User

The Singleton mode is a creation mode. It is the simplest mode in the design mode. Of course, it is used everywhere.

The Singleton mode ensures that a class has only one instance and provides a global access point to access it.

When you need to control the number of instances of a class and the caller can access it from a public, well-known access point, we can consider using the singleton mode.

We use UML to design the singleton mode. Of course, we will use UML to describe our design in the design part of the future design mode, which is more visualized.

From the UML design diagram, we can see that in order for a class to have only one Instance, it must create a static variable, and then we use a public static Instance () method to create it, however, to avoid the class's own constructor being able to create objects, we set the constructor to protected or private, so that the external can only use Instance () to create a static Singleton class. It seems that we have achieved our goal. Next we will look at the Code:

public class Singleton  {    private static Singleton instance;    protected Singleton()    public static Singleton Instance() {        if(instance != null) instance = new Singleton();        return instance;    }}

From this point of view, we can do the following steps to implement the singleton mode:

  1. Create a static variable in the class. The variable type is the current class;
  2. Create a public static method in the class so that you can use this method to create such static objects;
  3. Finally, set the constructor to protected or private.
Program List: the simplest Singleton class
<?phpclass Fruit{    static private $_color;    private function __construct()    {    }    static public function singleton() {        return isset(self::$_color) ? self::$_color : self::$_color = new self();    }}?>
Program List: scalable Singleton class

An extensible Singleton class seems impossible, but the following program is very close to this effect.

    <?phpclass Test extends Fruit {    public static function getInstance(){        return Fruit::getSingleton(get_class());    }}?><?phpclass Fruit {    /***********************     * HOW TO USE     *      * Inherit(extend) from Singleton and add getter:     *      *  //public getter for singleton instance     *     public static function getInstance(){     *        return Singleton::getSingleton(get_class());     *    }     *      */        private static $instanceMap = array();    //protected getter for singleton instances    protected static function getSingleton($className){        if(!isset(self::$instanceMap[$className])){                   $object = new $className;            //Make sure this object inherit from Singleton            if($object instanceof Fruit){                    self::$instanceMap[$className] = $object;            }            else{                throw SingletonException("Class '$className' do not inherit from Singleton!");            }        }        return self::$instanceMap[$className];    }            //protected constructor to prevent outside instantiation    protected function __construct(){    }        //denie cloning of singleton objects    public final function __clone(){        trigger_error('It is impossible to clone singleton', E_USER_ERROR);    }    }?><?phpclass Apple extends Fruit {        protected $rndId;        protected function __construct(){        $this->rndId = rand();    }            public function whatAmI(){        echo 'I am a Apple('.$this->rndId.')<br />';    }    public static function getInstance(){        return Fruit::getSingleton(get_class());    }}class GreenApple extends Apple {    public function whatAmI(){        echo 'I am a GreenApple('.$this->rndId.')<br />';    }        public static function getInstance(){        return Fruit::getSingleton(get_class());    }}$apple1 = Apple::getInstance();$apple2 = GreenApple::getInstance();$apple1->whatAmI();// should echo 'I am a A(some number)$apple2->whatAmI();// should echo 'I am a B(some number)$apple1 = Apple::getInstance();$apple2 = GreenApple::getInstance();$apple1->whatAmI();// should echo 'I am a A(same number as above)$apple2->whatAmI();// should echo 'I am a B(same number as above)// $a = new A();// this should fail// $b = new B();// this should fail?>

Program running result:

I am a Apple(4462)I am a GreenApple(8207)I am a Apple(4462)I am a GreenApple(8207)
Program List: Singleton class and its derived class
  <?phpclass Fruit{  // Hold an instance of the class  private static $instance;   // A private constructor; prevents direct creation of object  protected function __construct()  {      echo 'I am constructed';  }  // The singleton method  public static function singleton($classname = __CLASS__)  {      if (!isset(self::$instance)) {          self::$instance = new $classname;      }      return self::$instance;  }}class Apple extends Fruit {   public static function singleton()   {       return parent::singleton(__CLASS__); // NOTE The singleton method MUST return an instance.   }   public function showColor()   {       echo 'My Color is Red.';   }}$subclassInstance = Apple::singleton();$subclassInstance->showColor();?>

Program running result:

I am constructedMy Color is Red.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.