PHP design mode--Singleton mode

Source: Internet
Author: User

Singleton mode (Singleton pattern single-piece mode or single-element mode)

Singleton mode ensures that a class has only one instance, and instantiates itself and provides this instance to the entire system.

Singleton mode is a common design pattern, in the computer system, the thread pool, cache, log objects, dialog boxes, printers, database operations, graphics card drivers are often designed as a single case.

The singleton pattern is divided into 3 kinds: Lazy Type single case, a hungry man type single case, registration type single case.

The singleton mode has the following 3 features:

1. There can be only one instance.

2. You must create this instance yourself.

3. This instance must be provided to other objects.

So why use PHP singleton mode?

A major application of PHP is the application of the database to deal with the scene, there will be a large number of database operations in an application, the database handle connection to the database behavior, using a singleton mode can avoid a large number of new operations. Because each new operation consumes both system and memory resources.

In previous project development, the situation before using the singleton pattern was as follows:

--------------------------------------------------------------------------------------------------------------- ---------

Initialize a database handle
$db = new db (...);
For example, there is an application scenario where you add a user information
$db->adduserinfo ();
......
However, we are going to use this user information in another place, and this is where the database handle resource will be used.
......
function Test () {
$db = new db (...);
$db->getuserinfo ();
......
Some friends may say that you can use the Global keyword directly!
Global $db;
......

--------------------------------------------------------------------------------------------------------------- ---------

It is true that global solves the problem and acts as a singleton, but in OOP we reject the code. Because global has a security risk (the nature of the globally variable is not protected).

Global variables are one of the main causes of bugs encountered by object-oriented programmers. This is because global variables bundle classes in a particular environment, destroying encapsulation. If the new application does not guarantee that the same global variables are defined at the outset, a class that relies on a global variable cannot be extracted from an application and applied to a new application.

To be exact, the singleton pattern is just an improvement on global variables to avoid polluting namespaces with global variables that store unique instances. You cannot overwrite a single case with the wrong type of data. This protection is especially important in PHP versions that do not support namespaces. Because naming conflicts in PHP are captured at compile time, and the script stops running.

PHP Singleton Mode Example:

First look at the picture:

In the above object graph, there is a "singleton object", while "customer a", "Customer B" and "Customer C" are the three customer objects of the Singleton object. As you can see, all of the customer objects share a single Singleton object. And from the singleton to its own connection line, it can be seen that the Singleton object holds a reference to itself.

<?phpclass User {    //static variable holds global instance    private static $_instance = null;    Private constructor to prevent external instantiation of object Private function    __construct () {    }    //Private clone function to prevent external cloning of object private function    __clone () {    }    static method, single-instance unified Access Portal    static public function getinstance () {        if (empty (self::$_instance)) {            self::$_ Instance = new self (); or self::$_instance = new User ();        }        return self::$_instance;    }    Public Function GetName () {        echo ' Hello world! ';    }}? >

Advantages and disadvantages of the singleton model:

Advantages:

1. Improve the design of the system

2. is an improvement of the global variables

Disadvantages:

1. Difficult to debug

2. Hidden dependencies

3. Unable to overwrite a single case with the wrong type of data

PHP design mode--Singleton mode

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.