This article briefly introduces three most common design patterns in PHP: single-instance design patterns, factory design patterns, and Observer design patterns. I hope my friends will like this article to give you a brief introduction to the three most commonly used design modes in PHP: Singleton design mode, factory design mode, and Observer design mode. I hope my friends will like it.
This article describes the notes and summaries of the three commonly used design patterns in PHP. no matter which language is used for development, the design pattern is almost used. why do we need the design pattern? What is the role and significance of its birth for our developers?
I believe that the iOS developers will be familiar with the design model, right? For example, the singleton design mode, the factory design mode, the observer mode, and the MVC framework structure design mode.
Next, let's take a look at the three most common design patterns in PHP: Singleton design patterns, factory design patterns, and Observer design patterns.
Singleton design mode
The Singleton mode means that only one instance of this class exists in the application. once created, it will always exist in the memory!
The Singleton design mode is often used in database design. The Singleton mode is used to connect a database only once to prevent multiple database connections from being opened.
A singleton class should have the following features:
A singleton class cannot be directly instantiated and created, but can only be instantiated by the class itself. Therefore, to obtain such a restriction effect, the constructor must be marked as private to prevent classes from being instantiated.
A private static member variable is required to save the class instance and publish a public static method that can access the instance.
In PHP, to prevent others from cloning a singleton instance, an empty private__clone()Method.
Example of Singleton mode:
Factory Design model
The factory design pattern is usually used to create an instance dedicated to instantiation and returning its corresponding classes based on different input parameters or application configurations.
For example, if the rectangle and circle all have the same method, when we use the API provided by the base class to create an instance, we will automatically create an instance of the corresponding class by passing parameters, they all have the function of obtaining the length and area.
Width = $ width; $ this-> height = $ height;} publicfunctiongetArea () {return $ this-> width * $ this-> height;} publicfunctiongetCircumference () {return 2 * $ this-> width + 2 * $ this-> height;}/*** Circle */class Circle implementsInterfaceShape {private $ radius; function _ construct ($ radius) {$ this-> radius = $ radius;} publicfunctiongetArea () {return M_PI * pow ($ this-> radius, 2 );} publicfunctiongetCircumference () {return 2 * M_PI * $ this-> radius;}/*** shape factory class */class FactoryShape {publicstatic functioncreate () {switch (func_num_args ()) {case1: return newCircle (func_get_arg (0); case2: return newRectangle (func_get_arg (0), func_get_arg (1); default: # code... break ;}}$ rect = FactoryShape: create (5, 5); // object (Rectangle) #1 (2) {["width": "Rectangle ": private] => int (5) ["height": "Rectangle": private] => int (5)} var_dump ($ rect); echo"
"; // Object (Circle) #2 (1) {[" radius ":" Circle ": private] => int (4)} $ circle = FactoryShape :: create (4); var_dump ($ circle );Observer design pattern
The observer mode is a common design mode. when used properly, it will bring great convenience to the program. if used improperly, it will give people a hard-to-maintain idea.
What is the observer mode? An object can be observed by providing a method to allow another object, that is, the observer, to register itself. When an observed object changes, the message is sent to the registered observer. The operations performed by these observers using this information are irrelevant to the observed objects. The result is that objects can communicate with each other without understanding the cause. The Observer Mode is an event system, which means that this mode allows a class to observe the status of another class. when the observed class status changes, the observation class can receive notifications and make corresponding actions. The Observer mode allows you to avoid close coupling between components. Take the following example and you will understand it!
Observer_name;} functiononListen ($ sender, $ args) {}}// the observed class abstractclass Observable implementsInterfaceObservable {protected $ observers = array (); publicfunctionaddObserver ($ observer) {if ($ observerinstanceofInterfaceObserver) {$ this-> observers [] = $ observer ;}} publicfunctionremoveObserver ($ observer_name) {foreach ($ this-> observersas $ index => $ observer) {if ($ observer-> getObserverName () ===$ observer_name) {array_splice ($ this-> observers, $ index, 1); return ;}}}} // simulate A class A extendsObservable {publicfunctionaddListener ($ listener) {foreach ($ this-> observersas $ observer) {$ observer-> onListen ($ this, $ listener) ;}}// simulate an observer class B extendsObserver {protected $ observer_name = 'B'; publicfunctiononListen ($ sender, $ args) {var_dump ($ sender ); echo"
"; Var_dump ($ args); echo"
";}}// Simulate another observer class C extendsObserver {protected $ observer_name = 'C'; publicfunctiononListen ($ sender, $ args) {var_dump ($ sender); echo"
"; Var_dump ($ args); echo"
";}}$ A = new A (); // inject the observer $ a-> addObserver (new B (); $ a-> addObserver (new C ()); // you can see the observed information $ a-> addListener ('D'); // remove the observer $ a-> removeObserver ('B'); // Print the information: // object (A) #1 (1) {["observers": protected] => array (2) {[0] => object (B) #2 (1) {["observer_name": protected] => string (1) "B"} [1] => object (C) #3 (1) {["observer_name ": protected] => string (1) "C" }}// string (1) "D" // object (A) #1 (1) {["observers ": protected] => array (2) {[0] => object (B) #2 (1) {["observer_name": protected] => string (1) "B"} [1] => object (C) #3 (1) {["observer_name": protected] => string (1) "C" }}// string (1) "D"Summary
When I first entered the PHP world, I only learned about these basic design patterns and learned how to apply them! If there is something wrong with the article, please note in the comment that I will correct the article after making it clear!