This article introduces three common php design modes: Singleton mode, Factory mode, and observer mode. For more information, see. This article introduces three common php design modes: Singleton mode, Factory mode, and observer mode. For more information, see.
I. First, the singleton mode
The Singleton mode ensures that a class has only one instance and is instantiated and provided to the entire system. that is, only one instance of this class exists in the application.
The Singleton mode is usually used in instances that only allow the database to access objects, thus preventing multiple database connections from being opened. The Singleton mode is a common design mode. in computer systems, A thread pool, cache, log object, dialog box, printer, database operation, and graphics card driver is often designed as a singleton.
A singleton class should include the following:
Unlike normal classes, a singleton class cannot be directly instantiated, but can only be instantiated by itself. Therefore, to obtain such a restricted effect, the constructor must be marked as private.
To make a singleton class effective without being directly instantiated, you must provide such an instance for it. Therefore, the singleton class must have a private static member variable that can save the class and a public static method that can access the instance.
In PHP, to prevent the singleton class object from being cloned to break the preceding implementation form of Singleton classes, an empty private _ clone () method is also provided for the basics. Well, I will not talk much about it here.
The Singleton mode has the following three features:
1. you can only have one instance, you must have one constructor, and you must mark it as private.
2. you must create this instance and have a static member variable for the instance that saves the class.
3. you must provide this instance to other objects and have a public static method to access this instance.
A singleton class cannot be directly instantiated in other classes, but can only be instantiated by itself. It does not create instance copies, but returns a reference to the instance stored in the singleton class.
So why use the PHP Singleton mode?
One of the main application scenarios of PHP is the scenario where applications interact with databases. in one application, there will be a lot of database operations, and the database handles the connection to the database, the Singleton mode can avoid a large number of new operations. Because each new operation consumes system and memory resources.
In previous project development, before the Singleton mode was used:
// Initialize a database handle $ db = new DB (...); // for example, an application scenario is to add a comment $ db-> addComment ();...... // if we want to use this comment in another place, the database handle resource will be used ...... function comment () {$ db = new DB (...); $ db-> getCommentInfo ();...... // Some friends may say that the global keyword can be used directly! Global $ db ;......
It is true that global can solve the problem and also play the role of Singleton mode, but in OOP, we suggest rejecting this encoding. Because global has security risks (the nature of global variables is unprotected ).
Global variables are one of the main causes of bugs for object-oriented programmers. This is because global variables bind classes to a specific environment and destroy encapsulation. If the new application cannot guarantee that the same global variables are defined at the beginning, A class dependent on global variables cannot be extracted from an application and applied to a new application.
Specifically, the singleton mode is just an improvement on global variables to prevent global variables that store unique instances from polluting the namespace. You cannot overwrite a singleton with data of the error type. This protection is especially important in PHP versions that do not support namespaces. Because naming conflicts in PHP are captured during compilation and the script stops running.
We use the Singleton mode to improve the following example:
Class Single {private $ name; // declare a private instance variable private function _ construct () {// declare a private constructor to prevent external code from using new to create an object. } Static public $ instance; // declare a static variable (the only instance saved in the class) static public function getinstance () {// declare a static getinstance () method, used to check whether there is an instance object if (! Self: $ instance) self ::$ instance = new self (); return self ::$ instance;} public function setname ($ n) {$ this-> name = $ n;} public function getname () {return $ this-> name ;}}$ oa = Single: getinstance (); $ ob = Single: getinstance (); $ oa-> setname ('Hello php world'); $ ob-> setname ('good morning php '); echo $ oa-> getname (); // good morning phpecho $ ob-> getname (); // good morning php
Advantages and disadvantages of Singleton mode:
Advantages:
1. improved system design
2. it is an improvement on global variables.
Disadvantages:
1. difficult to debug
2. hidden dependency
3. unable to overwrite a singleton with data of the error type
II. factory model
The factory mode is a type that contains a method specifically used to create other objects. the factory class is crucial in the multi-state programming practice and allows dynamic replacement of classes, modifying the configuration usually makes the application more flexible. it is very important for advanced PHP developers who are familiar with the factory mode.
The factory mode is usually used to return different classes that conform to similar interfaces. a common usage of the factory is to create a multi-state provider, this allows us to decide which class should be instantiated based on the application logic or configuration settings. for example, we can use such a provider to extend a class without restructuring other parts of the application, to use the new extension name.
Generally, the Factory mode has a key structure and is named as the static method of Factory according to the general principle. However, this is only a principle, and the Factory method can be named arbitrarily, this static method can also accept any data parameter and must return an object.
You can use the factory class to create an object, the factory mode allows you to create a class dedicated to implementation and return other classes based on input parameters or application configurations, without directly using new, in this way, to change the type of the created object, you only need to change the factory,
Here is an example:
Name ;}} class C implements FetchName {private $ name = "CCCCC"; public function getname () {return $ this-> name ;}} class B implements FetchName {private $ name = "BBBBB"; public function getname () {return $ this-> name ;}} class D implements FetchName {private $ name = "DDDDD"; public function getname () {return $ this-> name ;}}$ o = Factory: fac (6 ); // call the method if ($ o instanceof FetchName) {echo $ o-> getname ();/ /DDDDD} $ p = Factory: fac (3); echo $ p-> getname (); // CCCCC?>
In my opinion, let's just put it simple. The PHP factory mode is to replace the new object operation with a factory method to facilitate expansion and use, when adding methods in the base class, you do not need to modify them in the factory class. you can directly use the input parameters. Specifically, you can skip the factory class modification, directly use the factory class to output the desired results. In traditional habits, if you want to generate a class, you can directly create an object in the code, such:
class Database{ } $db = new Database();
The following describes how to operate the factory mode:
Class Database {} // create a Factory class Factory {// Create a static method static function createDatabase () {$ db = new Database; return $ db ;}}
To create a database class, you can use the following method:
The advantage of the simple factory mode over the direct new object is that, for example, the Database class is used in many php files. when the Database class has changed, for example, if you modify the class name or some parameters, if you use the traditional method $ db = new Database to generate an object, all php file code containing the generated object must be modified. To use the factory mode, you only need to modify it in the factory method or class. In addition, the factory model is the basis of other design models.
The preceding simple factory model is further optimized, for example:
Use factory production objects:
The simple factory mode is also called the static factory method mode. We can see from the naming that this mode must be very simple. Its purpose is to define an interface for creating objects.
To understand the concept of the factory model, we 'd better talk about the hard work of many developers engaged in large-scale systems. A problem occurs when you change a code snippet. other parts of the system, which you once thought were completely unrelated, may also cause cascading damages.
This problem lies in tight coupling. Functions and classes in a certain part of the system depend heavily on the behavior and structure of functions and classes in other parts of the system. You need a set of modes to enable these classes to communicate with each other, but do not want to closely bind them together to avoid interlocking.
In large systems, many codes depend on a few key classes. It may be difficult to change these classes. For example, assume that you have a User class to read from a file. You want to change it to other classes read from the database, but all code references the original class read from the file. At this time, it is very convenient to use the factory model.
Check the instance:
The traditional method uses the User class, which is generally like this:
At this time, due to new requirements, the User class code changes when a new parameter or User class name needs to be added to the User class, that is:
pre."Fantasy"; }}?>
Next, a terrible thing happened. if the previous 100 pages referenced the previous User class, the 100 pages should be changed accordingly:
// On the page 1 $ obj = new User (1, 'AAA'); // On the page 2 $ obj = new User (2, 'AAA '); // On the page 3 $ obj = new User (3, 'AAA ');...
It was originally a small change, but due to the tight coupling, the change was vomiting. The factory mode can avoid this situation:
// The User class is the class UserFactory {public static function Create ($ id) {return new User ($ id) ;}// page 1 $ uo1 = UserFactory :: create (1); // page 2 $ uo12 = UserFactory: Create (2 );....
At this time, the demand changes, and the User class also changes:
pre."Jack"; }}?>
However, we no longer need to modify the 100 pages. we only need to change the factory class:
//class UserFactory{ public static function Create( $id,$pre = 'aaa' ) { return new User( $id ,$pre); }}
There is no need to make any changes to the other 100 pages, which is the benefit of the factory design model. Take a look at the UML diagram:
_ Observers [] = $ sub;} public function trigger () {/* unified external access */if (! Empty ($ this-> _ observers) {foreach ($ this-> _ observers as $ observer) {$ observer-> update ();}}}} /*** the interface implemented by the Observer */interface Observerable {public function update ();} class Subscriber implements Observerable {public function update () {echo "Callback \ n" ;}}?>
The following is the test code:
/* Test */$ paper = new Paper (); $ paper-> register (new Subscriber (); // $ paper-> register (new Subscriber1 ()); // $ paper-> register (new Subscriber2 (); $ paper-> trigger ();
Summary
When a new object is to be filled in, you only need to register it in the topic (also called the observer) (there are many registration methods, you can also construct, or register in the interface accessed by the framework), and then implement code directly in the interface of the new object. This reduces the coupling between the subject object and the observer object.
A good design pattern does not directly go into your code, but into your brain.
For more articles about three common PHP design patterns, refer to the Chinese PHP website!