What is PHP singleton mode? An explanation of the usage of the singleton pattern

Source: Internet
Author: User
Starting from the concept of design pattern, this paper tells the singleton pattern in PHP design pattern, which are basic knowledge, and give beginners a chance to improve.

This series of articles summarizes the application of design patterns in PHP, which is the first singleton pattern of the creation pattern.

Introduction of Design pattern
First, let's get to know what design patterns are:
Design patterns are a set of reusable, easily understandable, and reliable code design experiences.
Design mode is not a Java patent, we use the object-oriented approach in PHP can also be very good using 23 design patterns.
So what do we often say about architecture, frameworks, and design patterns?
Architecture is a set of architecture, is the overall solution of the project, the framework is reusable semi-finished software, is the specific program code. Architecture generally involves the use of frameworks to speed up and optimize the resolution of certain parts of the problem, while good framework code uses a lot of design patterns.

Ii. several principles for refining design patterns:

Open and Close principle: modules should be opened for expansion and closed for modification.
The principle of substitution on the Richter scale: If the parent class is called, then the subclass will be fully operational.
Dependency reversal principle: Abstract does not rely on details, interface programming, passing parameters as far as possible to refer to high-level classes.
Interface Isolation principle: each interface is responsible for only one role.
Synthesis/Aggregation multiplexing principle: do not misuse inheritance if you want to use composition/aggregation as much as possible.

Third, the function of design mode?

Design patterns can solve
Replace disorganized code to form a good code style
The code is easy to read and engineers can easily understand
Add new features without modifying the interface, scalability is strong
Good stability, generally do not appear unknown problems
Design mode does not resolve:
Design patterns are templates used to organize your code, not directly called libraries;
Design patterns are not the most efficient, but the readability and maintainability of the code is more important;
Do not blindly pursue and apply design patterns, re-construction when more consideration;

Iv. Classification of design patterns
1. Creation mode:
Singleton mode, Factory mode (Simple factory, factory method, abstract factory), creator mode, prototype mode.
2. Structural mode:
Adapter mode, bridge mode, decoration mode, combination mode, appearance mode, enjoy meta mode, proxy mode.
3. Behavioral Mode:
Template method mode, command mode, iterator mode, observer pattern, Mediator mode, Memo mode, interpreter mode, state mode, policy mode, responsibility chain mode, visitor mode.
V. Creation of Design Patterns
1. Single Case mode
Purpose: To ensure that a class has only one instance and provides a global access point to access it.
Application Scenario: Database connection, cache operation, distributed storage.

The code is as follows:

/** * Singleton mode */class dbconn{private static $_instance = null;       protected static $_counter = 0;       protected $_db;       Privatization constructor, does not allow externally created instance private function construct () {self::$_counter + = 1;                     Public Function getinstance () {if (self::$_instance = = null) {              Self::$_instance = new Dbconn ();       } return self::$_instance; } Public Function connect () {echo "Connected:". ( Self::$_counter). "              n ";       return $this->_db; }}/* * When you do not use singleton mode, delete the constructor's private after testing, after the second call to the constructor, _counter becomes 2*///$conn = new Dbconn (),//$conn->connect ();//$conn = new Dbconn ();//$conn->connect ();//The new object cannot be used directly after using singleton mode, must be called getinstance get $conn = Dbconn::getinstance (); $db = $conn Connect ();//The second call is the same instance, _counter or 1$conn = Dbconn::getinstance (); $db = $conn->connect (); 

Special Note: There is an if judgment in this getinstance and then generate the object, in the multithreaded language there will be concurrency problems. For example, there are two solutions for Java, the method plus the Synchronized keyword becomes synchronous, or the initialization of _instanc is put in advance to the class member variable definition, but these 2 ways PHP is not supported. However, because PHP does not support multithreading, you do not need to consider this issue.

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.