PHP duty mode singleton mode _php tutorial

Source: Internet
Author: User
Patterns are very important for object-oriented development. A pattern can help us create objects that are capable of fulfilling a particular task and become the responsibility of the class. The pattern also allows us to modify a class, but does not need to modify the code that is related to this class, which is called the polymorphism of the class.

The singleton mode, also known as the responsibility mode, is used to create a single functional access point in the application. Let's explore and master the idea of a single case and apply it in a solid way.

In complex systems, using singleton mode is particularly useful for maintaining synchronization of application state. All singleton classes have at least the following three elements:

    • A constructor that is marked private.
    • A static member variable that holds an instance of the class.
    • A public static method that accesses this instance.

Program list: The class of the singleton mode

 '; $test->showcolor ();//This would issue an e_user_error.//$test _clone = Clone $test;? >

Program Run Result:

I am constructedmy color is!

Some special things can be seen from this program. Unlike ordinary classes, a singleton class cannot be instantiated directly, it can only be instantiated by itself. To achieve this effect, the __construct () method must be marked private. If you attempt to construct an object with the private constructor, you will get an access level error.

So how does a singleton class work? The Singleton class is to provide an instance to other classes and invoke various methods with it. The Singleton class returns a reference through an instance of the internal store, so the Singleton class does not repeatedly consume memory and system resources, allowing the rest of the application to use resources better. So, your database access is best built with a singleton pattern, so you don't create too many database connection instances to make your system run faster.

An empty __clone () method is necessary to prevent the object from being copied or cloned.

Self:: $instance can detect if the class has been initialized. If the static member of the Save instance is empty or is not yet an instance of the class itself, the instance is created and saved to the variable that holds the instance.

Program list: Single instance with no private constructor

An not strict Singleton, there is no private constructor, and there is no reference to itself. I don't know if it's a model.

  
 0 && $value <) Self:: $height = $value;  The Public Function setweight ($value) {if ($value > 0 && $value <) Self:: $weight = $value; } public Function __tostring () {return ' fruit[height= '. Self:: $height. ', weight= '. Self:: $weight.  ']';  }}//try to set data before any objects is createdfruit:: $height = n; $msm 1 = fruit::getinstance ();           Use the getinstance () method$msm2 = new Fruit ();                           Use the default constructor$msm2->setweight (78); Set data with an instantiated Objectecho $MSM 1. '
'; Echo $msm 2. '
'; Echo fruit::getinstance (). '
'; Echo (new Fruit ());? >

Program Run Result:

Fruit[height=55, weight=78]fruit[height=55, weight=78]fruit[height=55, weight=78]fruit[height=55, weight=78]

Program List: Database connection Responsibilities

 
  _db = Pg_connect (' dbname=example_db ');} Private __clone () {};p ublic static function getinstance () {if (! (Self::$_instance instanceof Self)) {self::$_instance = new self ();} return self::$_instance;} Public Function Query ($sql) {return pg_query ($this->_db, $sql);}}? >

How do I use this singleton class?

$db = Database::getinstance (); $db->query (' SELECT * from example_table ');

That is, there are some differences between methods of acquiring objects, and there is nothing special about using them with other objects.

http://www.bkjia.com/PHPjc/752400.html www.bkjia.com true http://www.bkjia.com/PHPjc/752400.html techarticle patterns are very important for object-oriented development. A pattern can help us create objects that are capable of fulfilling a particular task and become the responsibility of the class. The pattern also allows us to modify a class, ...

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