PHP single-state design mode

Source: Internet
Author: User
PHP single-state design mode Title: single-state design mode, single-case design mode, and single-piece design mode (don't be asked during the interview)

Concept:Singleton (Singleton) mode is mainly used to ensure that only one Class exists in an object-oriented programming language.

Purpose:In many operations, such as creating a directory database connection, such single-threaded operations are required.

Implementation method:

(1) If you want a class to have only one object, you must first prevent the class from creating objects and be cloned (_ clone ), therefore, we need to privatize the constructor and clone methods.

(2) provide a static method in the class to create an object

(3) provide a static attribute in the class to store the instantiated object (if the object exists, it will not be instantiated, so as to ensure that the object is instantiated only once)

Example:

Class Instance {// static variable save global instance private static $ _ Instance = null; // private constructor to prevent external instantiation object private function _ construct () {echo 'when I see it several times, it indicates how many times I have been created';} // private clone function to prevent external clone object private function _ clone () {} // static method. in Singleton mode, the access entry static public function getInstance () {if (is_null (self ::$ _ instance) {self :: $ _ instance = new self ();} return self: $ _ instance;} Instance: getInstance (); Instance :: getInstance ();

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.