Home > Article > Backend Development > Simple practical examples of various PHP design patterns
I have always felt that frameworks, versions, and even languages really don’t matter to a coder. Mastering a particularly advanced framework or a new, minority language really doesn’t matter, because you It’s okay, it’s okay if I want to spend time, everyone is like this. Therefore, the basic ones are particularly important, namely algorithms and data structures, and then good design patterns.
Single case mode features
$_instance must be declared as a static private variable
Constructors and clone functions must be declared as private. This is to prevent external programs from adding new classes and thus losing the meaning of the singleton mode.
The getInstance() method must be declared as public. This method must be called to return a reference to a unique instance
:: The operator can only access static variables or static functions
Single PHP The example mode is relative, because PHP's interpretation and execution mechanism causes all related resources to be recycled after each PHP page is interpreted and executed.
<?php header("Content-type: text/html; charset=utf-8"); class single{ public static $arr=array('host'=>'XXX','user'=>'XXX','password'=>'XXX'); private static $_instance =null; private function __construct(){} private function __clone(){} static public function getInstance(){ if(self::$_instance== null || isset(self::$_instance)){ self::$_instance= new self; } return self::$_instance; } public function showSomething(){ return self::$arr; } } /////////////////////test/////////////// $a=single::getInstance(); print_r(single::getInstance()->showSomething()); ?>
Factory pattern
The factory class is a class specially used to create other objects. The factory class is very important in the practice of polymorphic programming. It allows dynamic replacement of classes and modification of configurations, making the application more flexible. Mastering the factory pattern is essential for web development.
Features:
The factory pattern is usually used to return different classes similar to interfaces. A common use of factories is to create polymorphic providers.
Usually the factory pattern has a key construct, which is a static method generally named factory. This static method can accept any number of parameters and must return an object.
The factory pattern is further divided into:
Simple Factory Pattern
Factory Method Pattern
Abstract Factory Pattern )
Simple factory mode: used to produce any product in the same hierarchical structure. There is nothing you can do about adding new products
Factory model: used to produce fixed products in the same hierarchical structure. (Supports adding any product)
Abstract factory: used to produce all products of different product families. (There is nothing you can do about adding new products; support adding product families)
<?php //简单工厂模式 header("Content-type: text/html; charset=utf-8"); class simpale{ public function calculate($num1,$num2,$operator){ try { $result=0; switch ($operator){ case '+': $result= $num1+$num2; break; case '-': $result= $num1-$num2; break; case '*': $result= $num1*$num2; break; case '/': if ($num2==0) { throw new Exception("除数不能为0"); } $result= $num1/$num2; break; } return $result; } catch (Exception $e){ echo "您输入有误:".$e->getMessage(); } } } //工厂方法模式 interface people { function jiehun(); } //定义接口 class man implements people{ public $ring=null; public $car=null; public $house=null; public function getAllthing(){ $this->ring='10000'; $this->car='100000'; $this->house='1000000'; } public function jiehun() { if($this->ring && $this->car && $this->house) echo '我可以结婚了<br>'; else echo '我是臭屌丝,还不能结婚<br>'; } } class women implements people { public $face='ugly'; public function getAllthing(){ $this->face='nice'; } public function jiehun() { if($this->face =='nice') echo '我可以结婚了<br>'; else echo '我是臭屌丝,还不能结婚<br>'; } } interface createpeople { // 注意了,这里是工厂模式本质区别所在,将对象的创建抽象成一个接口。 public function create(); } class FactoryMan implements createpeople{ public function create() { return new man; } } class FactoryWomen implements createpeople { public function create() { return new women; } } class Client { // 简单工厂里的静态方法 public function test() { $Factory = new FactoryMan; $man = $Factory->create(); $man->jiehun(); $Factory = new FactoryWomen; $woman = $Factory->create(); $woman->getAllthing(); $woman->jiehun(); } } /////////////test//////////// $f = new Client; $f->test(); //抽象模式就是在工厂模式下接口中添加相应的不同方法即可 ?>
Strategy Pattern
Strategy pattern is the behavior pattern of an object, 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 characteristics of the strategy pattern:
Define the abstract role class (define the common abstract method of each implementation)
Define the specific strategy class (the common method of the specific implementation parent class)
Define environment role class (privately declare abstract role variables, overload construction methods, execute abstract methods)
<?php abstract 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 (); } } ///////////////test//////////////// $bro = new Browser (); echo $bro->call (new ieAgent );
Related recommendations:
Combination of PHP design patterns Pattern and case sharing
Common PHP design pattern sharing
Introduction to commonly used design patterns in PHP and their usage examples
The above is the detailed content of Simple practical examples of various PHP design patterns. For more information, please follow other related articles on the PHP Chinese website!