Home>Article>Backend Development> What are the design patterns of php
The singleton mode solves the problem of how to create a unique object instance in the entire project, and the factory mode solves the problem of how to create an instance object without using new. Methods. (php video tutorial)
Singleton mode allows only one object of a certain class to be created. Constructor private modification,
Declares a static getInstance method, and creates an instance of the object in this method. If the instance already exists, it is not created. For example, you only need to create a database connection.
Factory mode, factory method or class generates objects instead of new directly in the code.
Using the factory pattern can avoid changing the name or method of a class and modifying its name or parameters in all the code that calls this class.
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. Go directly to visit anywhere.
Encapsulate 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
MySQL conn = $conn; } function query($sql) { $res = mysql_query($sql, $this->conn); return $res; } function close() { mysql_close($this->conn); } }
MySQLi conn = $conn; } function query($sql) { return mysqli_query($this->conn, $sql); } function close() { mysqli_close($this->conn); } }
PDO conn = $conn; } function query($sql) { return $this->conn->query($sql); } function close() { unset($this->conn); } }
Through the above cases, there are three sets of APIs for database interaction between PHP and MySQL. Different APIs may be used in different scenarios, so if the developed code changes to another environment, its database API may need to be changed, then all the code must be rewritten. After using the adapter mode, a unified API can be used to shield the underlying layer. The API differences bring about the need to rewrite the code after the environment changes.
Strategy pattern encapsulates a specific set of behaviors and algorithms into classes to adapt to certain specific contexts.
eg: If there is an e-commerce website system, male and female users need to jump to different product categories, and all advertising spaces display different ads. In traditional codes, various if else judgments are added to the system in a hard-coded manner. If one day a user is added, the code needs to be rewritten. Using the policy mode, if you add a new user type, you only need to add a policy. Everything else just requires a different strategy.
First declare the interface file of the strategy and stipulate the included behavior of the strategy. Then, define each specific strategy implementation class.
UserStrategy.php
FemaleUser.php
MaleUser.php
Page.php//执行文件 strategy->showAd(); echo "
"; echo "Category"; $this->strategy->showCategory(); echo "
"; } function setStrategy(UserStrategy $strategy){ $this->strategy=$strategy; } } $page = new Page(); if(isset($_GET['male'])){ $strategy = new MaleUser(); }else { $strategy = new FemaleUser(); } $page->setStrategy($strategy); $page->index();
执行结果图:
总结:
通过以上方式,可以发现,在不同用户登录时显示不同的内容,但是解决了在显示时的硬编码的问题。如果要增加一种策略,只需要增加一种策略实现类,然后在入口文件中执行判断,传入这个类即可。实现了解耦。
实现依赖倒置和控制反转(有待理解)
通过接口的方式,使得类和类之间不直接依赖。在使用该类的时候,才动态的传入该接口的一个实现类。如果要替换某个类,只需要提供一个实现了该接口的实现类,通过修改一行代码即可完成替换。
1:观察者模式(Observer),当一个对象状态发生变化时,依赖它的对象全部会收到通知,并自动更新。
2:场景:一个事件发生后,要执行一连串更新操作。传统的编程方式,就是在事件的代码之后直接加入处理的逻辑。当更新的逻辑增多之后,代码会变得难以维护。这种方式是耦合的,侵入式的,增加新的逻辑需要修改事件的主体代码。
3:观察者模式实现了低耦合,非侵入式的通知与更新机制。
定义一个事件触发抽象类。
EventGenerator.php observers[]=$observer; } function notify(){ foreach ($this->observers as $observer){ $observer->update(); } } }
定义一个观察者接口
Observer.php
addObserver(new Observer1()); $event->addObserver(new Observer2()); $event->triger(); $event->notify();
当某个事件发生后,需要执行的逻辑增多时,可以以松耦合的方式去增删逻辑。也就是代码中的红色部分,只需要定义一个实现了观察者接口的类,实现复杂的逻辑,然后在红色的部分加上一行代码即可。这样实现了低耦合。
原型模式(对象克隆以避免创建对象时的消耗)
1:与工厂模式类似,都是用来创建对象。
2:与工厂模式的实现不同,原型模式是先创建好一个原型对象,然后通过clone原型对象来创建新的对象。这样就免去了类创建时重复的初始化操作。
3:原型模式适用于大对象的创建,创建一个大对象需要很大的开销,如果每次new就会消耗很大,原型模式仅需要内存拷贝即可。
Canvas.php data = $data; } function rect($x1, $y1, $x2, $y2) { foreach($this->data as $k1 => $line) { if ($x1 > $k1 or $x2 $char) { if ($y1>$k2 or $y2data[$k1][$k2] = '#'; } } } function draw(){ foreach ($this->data as $line){ foreach ($line as $char){ echo $char; } echo "
;"; } } }
Index.php init(); / $canvas1 = new Canvas(); // $canvas1->init(); $canvas1 = clone $c;//通过克隆,可以省去init()方法,这个方法循环两百次 //去产生一个数组。当项目中需要产生很多的这样的对象时,就会new很多的对象,那样 //是非常消耗性能的。 $canvas1->rect(2, 2, 8, 8); $canvas1->draw(); echo "-----------------------------------------
"; // $canvas2 = new Canvas(); // $canvas2->init(); $canvas2 = clone $c; $canvas2->rect(1, 4, 8, 8); $canvas2->draw();
执行结果:
1:装饰器模式,可以动态的添加修改类的功能
2:一个类提供了一项功能,如果要在修改并添加额外的功能,传统的编程模式,需要写一个子类继承它,并重写实现类的方法
3:使用装饰器模式,仅需要在运行时添加一个装饰器对象即可实现,可以实现最大额灵活性。
The above is the detailed content of What are the design patterns of php. For more information, please follow other related articles on the PHP Chinese website!