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:
<?phpabstract class baseAgent { //抽象策略类 abstract function PrintPage(); } //用于客户端是IE时调用的类(环境角色) class ieAgent extends baseAgent { function PrintPage() { return 'IE'; } } //用于客户端不是IE时调用的类(环境角色) class otherAgent extends baseAgent { function PrintPage() { return 'not IE'; } } class Browser { //具体策略角色 public function call($object) { return $object->PrintPage (); } } $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!

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python are both high-level programming languages that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values and handle functions that may return null values.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version
Useful JavaScript development tools