[Reading Notes-reconstruction and mode] Singleton Mode

Source: Internet
Author: User

The article goes deep into PHP object-oriented, patterns and practices and points out that global variables are object-orientedProgramOne of the main causes of bugs encountered by members is that global variables bundle classes in a specific environment and disrupt encapsulation. However, in order to make all classes accessible to an object, we will not hesitate to tolerate the defects of global access.

To sum up, you do not need to use global variables and want to make every class accessible to objects. The key points of the problem are:

1. The object should be used by any object in the system.

2. objects should not be stored in global variables that will be rewritten.

3. The system should not contain more than one variable.

To solve this problem, you can use the singleton mode.

The implementation idea of the singleton mode is to set the class constructor to private permission, and indirectly instantiate the object using a static method and static attribute.

Class Singleton {Private Static $ instance = NULL; private $ props = array (); Private function _ construct () {} public static function getinstance () {If (empty (self:: $ instance) {self ::$ instance = new self ();} return self ::$ instance;} public function setprop ($ prop, $ value) {$ this-> props [$ prop] = $ value;} public function getprop ($ prop) {return $ this-> props [$ prop];} private function _ set ($ prop, $ value) {// omitted} private function _ Get () {// omitted} private function _ clone () {// omitted }}

The UML diagram of the singleton mode is as follows:

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.