PHP design mode-Singleton mode

Source: Internet
Author: User
PHP design mode-Singleton mode statement: This series of blog reference material "big talk Design Mode", author Cheng Jie.

The Singleton mode is also called the single-state mode. it is the simplest of the 23 design modes. his core idea can be known from his name, the Singleton mode is that there is only one such object in the system, and there is only one object. in Java or C #, Singleton mode generally has two types: lazy and hungry, however, in PHP, the lazy style is commonly used. because PHP is single-threaded, there is no dual verification for lazy style.

Lazy code:

Test code:

$ Single1 = Singleton: getInstance (); $ single1-> age = 22; $ single2 = Singleton: getInstance (); $ single2-> age = 24; echo "age of variable 1: {$ single1-> age}
"; Echo" age of variable 2: {$ single2-> age}

We can see that the age of the variable $ single1 and $ single2 is 24, indicating that the variable $ single1, $ single2 is a variable, and the Singleton class is Singleton.

With the above code, I can organize three steps to write the Singleton mode:

1. create a static variable

2. private constructor and clone function to prevent external calls

3. provide a static method that can be called externally to instantiate the static variable created in the first step.

Obviously, the single-instance mode is applicable when only one object is needed in the system, such as the Bean factory of Spring in Java and the database connection in PHP, as long as this requirement is met, the singleton mode is used first.

PHP object-oriented design model

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: 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.