PHP design mode-singleton mode (singleton)

Source: Internet
Author: User

Before you learn this singleton mode, please choose to read another design mode

PHP design mode-Simple Factory mode (static Factory method mode)

PHP design mode-factory method mode (polymorphism Factory mode) (virtual construction sub-mode)

PHP design mode-Abstract Factory mode

As an object's creation mode, Singleton mode ensures that a class has only one instance, and instantiates it itself and provides it to the entire system, a class called a singleton class

The singleton mode (singleton) has three features
1. Only one instance of a class
2. It must create this instance on its own
3. It must provide this instance to the entire system on its own

Legend:

code example:

Singleton mode is divided into lazy singleton patterns in Java | a hungry man single-case mode

However, the A hungry man singleton mode is not available in PHP, and I will list the code below, which will prompt the error at run-time. Here is just a concept of usage.

A hungry man single-case mode:

1 //This is the A Hungry man single-case pattern .2 //But in PHP, this is not allowed to be practical. So we're basically talking about PHP's lazy singleton pattern.3 classTest {4     Private Static $_instance=NewSelf ();5 6      Public Static functiongetinstance () {7         returnSelf::$_instance;8     }9 Ten     Private function__construct () { One         //Check instantiation A         Echo"Instance\n"; -     } -  the } - $a= Test::getinstance (); - Var_dump($a);

Lazy single-case mode:

1 //Lazy Single-case mode2 3 classTest {4     Private Static $_instance;5 6      Public Static functiongetinstance () {7         if(!self::$_instance){8Self::$_instance=NewSelf ();9         }Ten         returnSelf::$_instance; One     } A  -     Private function__construct () { -         //Check instantiation the         Echo"Instance\n"; -     } -  - } +  - $a= Test::getinstance (); + Var_dump($a);

PHP design mode-singleton mode (singleton)

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.