Home > Article > Backend Development > Detailed explanation of five common PHP design patterns
Strategy pattern
Strategy pattern is the behavior pattern of an object and is intended to encapsulate a set of algorithms. Dynamically select the required algorithm and use it.
Strategy mode refers to a mode involving decision-making control in the program. The strategy pattern is very powerful because the core idea of this design pattern itself is the polymorphic idea of object-oriented programming.
Three roles of strategy mode:
1. Abstract strategy role
2. Specific strategic roles
3. Environment role (reference to abstract strategy role)
Implementation steps:
1. Define abstract role classes (define common abstract methods for each implementation)
2. Define a specific strategy class (concretely implement the common method of the parent class)
3. Define environment role classes (privately declare abstract role variables, overload constructors, execute abstract methods)
Just outside the field of programming, there are many examples of the Strategy pattern. For example:
If I need to go to work from home in the morning, I can have several strategies to consider: I can take the subway, take the bus, walk or other ways. Each strategy achieves the same results but uses different resources.
Code examples of strategy pattern:
58994ff7fd10843fdb2333da92484a29PrintPage (); } } $bro = new Browser (); echo $bro->call ( new ieAgent () ); ?>
Factory pattern
Factory pattern is our most commonly used instantiation object pattern , is a mode that uses factory methods to replace new operations.
The advantage of using the factory pattern is that if you want to change the instantiated class name, etc., you only need to change the content of the factory method, and you do not need to find the specific instantiation places in the code one by one (new ) has been modified. Provides a flexible dynamic expansion mechanism for the system structure and reduces coupling.
<?php header('Content-Type:text/html;charset=utf-8'); /** *简单工厂模式(静态工厂方法模式) */ /** * Interface people 人类 */ interface people { public function say(); } /** * Class man 继承people的男人类 */ class man implements people { // 具体实现people的say方法 public function say() { echo '我是男人<br>'; } } /** * Class women 继承people的女人类 */ class women implements people { // 具体实现people的say方法 public function say() { echo '我是女人<br>'; } } /** * Class SimpleFactoty 工厂类 */ class SimpleFactoty { // 简单工厂里的静态方法-用于创建男人对象 static function createMan() { return new man(); } // 简单工厂里的静态方法-用于创建女人对象 static function createWomen() { return new women(); } } /** * 具体调用 */ $man = SimpleFactoty::createMan(); $man->say(); $woman = SimpleFactoty::createWomen(); $woman->say();
Single case mode
Single case mode ensures that there is only one instance of a class, and it instantiates itself and provides this instance to the entire system .
The singleton mode is a common design pattern. In computer systems, thread pools, caches, log objects, dialog boxes, printers, database operations, and graphics card drivers are often designed as singletons.
There are three types of singleton modes: lazy-style singleton, hungry-style singleton, and registration-style singleton.
The singleton mode has the following three characteristics:
1. There can only be one instance.
2. You must create this instance yourself.
3. This instance must be provided to other objects.
So why use PHP singleton mode?
One of the main application scenarios of PHP is the scenario where the application deals with the database. In an application, there will be a large number of database operations. For the behavior of connecting the database handle to the database, using the singleton mode can avoid a large number of new operations. Because every new operation consumes system and memory resources.
class Single { private $name;//声明一个私有的实例变量 private function __construct(){//声明私有构造方法为了防止外部代码使用new来创建对象。 } static public $instance;//声明一个静态变量(保存在类中唯一的一个实例) static public function getinstance(){//声明一个getinstance()静态方法,用于检测是否有实例对象 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 world'); $ob->setname('good morning'); echo $oa->getname();//good morning echo $ob->getname();//good morning
Registration mode
Registration mode solves global sharing and exchange objects. The created object is hung on a globally usable array. When needed, it can be obtained directly from the array. Register the object in the global tree. Access directly from anywhere.
<?php class Register { protected static $objects; function set($alias,$object)//将对象注册到全局的树上 { self::$objects[$alias]=$object;//将对象放到树上 } static function get($name){ return self::$objects[$name];//获取某个注册到树上的对象 } function _unset($alias) { unset(self::$objects[$alias]);//移除某个注册到树上的对象。 } }
Adapter pattern
Encapsulates various completely different functional interfaces into a unified API.
There are three database operations in PHP: MySQL, MySQLi, and PDO. They can be unified using the adapter mode, so that different database operations can be unified into the same API. Similar scenarios include cache adapters, which can unify different cache functions such as memcache, redis, file, apc, etc. into a consistent one.
First define an interface (with several methods and corresponding parameters). Then, if there are several different situations, just write several classes to implement the interface. Unify functions that perform similar functions into a consistent method.
#接口 IDatabase <?php namespace IMooc; interface IDatabase { function connect($host, $user, $passwd, $dbname); function query($sql); function close(); }
MySQL
<?php namespace IMooc\Database; use IMooc\IDatabase; class MySQL implements IDatabase { protected $conn; function connect($host, $user, $passwd, $dbname) { $conn = mysql_connect($host, $user, $passwd); mysql_select_db($dbname, $conn); $this->conn = $conn; } function query($sql) { $res = mysql_query($sql, $this->conn); return $res; } function close() { mysql_close($this->conn); } }
MySQLi
<?php namespace IMooc\Database; use IMooc\IDatabase; class MySQLi implements IDatabase { protected $conn; function connect($host, $user, $passwd, $dbname) { $conn = mysqli_connect($host, $user, $passwd, $dbname); $this->conn = $conn; } function query($sql) { return mysqli_query($this->conn, $sql); } function close() { mysqli_close($this->conn); } }
Observer Pattern
1: Observer Pattern ( Observer), when the state of an object changes, all objects that depend on it will be notified and automatically updated.
2: Scenario: After an event occurs, a series of update operations must be performed. The traditional programming method is to add processing logic directly after the event code. When the updated logic increases, the code will become difficult to maintain. This method is coupled and intrusive, and adding new logic requires modifying the main code of the event.
3: The observer pattern implements a low-coupling, non-intrusive notification and update mechanism.
Define an event trigger abstract class.
EventGenerator.php <?php require_once 'Loader.php'; abstract class EventGenerator{ private $observers = array(); function addObserver(Observer $observer){ $this->observers[]=$observer; } function notify(){ foreach ($this->observers as $observer){ $observer->update(); } } }
Define an observer interface
Observer.php <?php require_once 'Loader.php'; interface Observer{ function update();//这里就是在事件发生后要执行的逻辑 } //一个实现了EventGenerator抽象类的类,用于具体定义某个发生的事件
Implementation:
require 'Loader.php'; class Event extends EventGenerator{ function triger(){ echo "Event<br>"; } } class Observer1 implements Observer{ function update(){ echo "逻辑1<br>"; } } class Observer2 implements Observer{ function update(){ echo "逻辑2<br>"; } } $event = new Event(); $event->addObserver(new Observer1()); $event->addObserver(new Observer2()); $event->triger(); $event->notify();
Related recommendations:PHP tutorial
The above is the detailed content of Detailed explanation of five common PHP design patterns. For more information, please follow other related articles on the PHP Chinese website!