What are the design patterns of php

步履不停
Release: 2023-02-23 07:46:02
Original
2399 people have browsed it

What are the design patterns of php

Design Pattern

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)

Single case mode

  1. $_instance must be declared as a static private variable
  2. Constructor and destructor It must be declared as private to prevent external programs from creating new classes and thereby losing the meaning of the singleton mode
  3. The getInstance() method must be set to public, and this method must be called to return a reference to the instance
  4. : :The operator can only access static variables and static functions
  5. new objects will consume memory
  6. Usage scenarios: The most commonly used place is database connection.
  7. After using the singleton mode to generate an object, the object can be used by many other objects.
  8. Private __clone() method prevents cloning of objects

Singleton mode allows only one object of a certain class to be created. Constructor private modification, <br>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 mode, factory method or class generates objects instead of new directly in the code. <br>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.

<br>
Copy after login

What are the design patterns of php

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. Go directly to visit 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]);//移除某个注册到树上的对象。
    }
}
Copy after login

Encapsulate various completely different functional interfaces into a unified API. <br>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. <br>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();
}
Copy after login
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);
    }
}
Copy after login
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);
    }
}
Copy after login
PDO
<?php namespace IMooc\Database;
use IMooc\IDatabase;
class PDO implements IDatabase
{
    protected $conn;
    function connect($host, $user, $passwd, $dbname)
    {
        $conn = new \PDO("mysql:host=$host;dbname=$dbname", $user, $passwd);
        $this->conn = $conn;
    }
function query($sql)
    {
        return $this->conn->query($sql);
    }

    function close()
    {
        unset($this->conn);
    }
}
Copy after login

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

Strategy pattern encapsulates a specific set of behaviors and algorithms into classes to adapt to certain specific contexts. <br>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. <br>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
<?php /*
 * 声明策略文件的接口,约定策略包含的行为。
 */
interface UserStrategy
{
    function showAd();
    function showCategory();
}
Copy after login
FemaleUser.php
<?php require_once &#39;Loader.php&#39;;
class FemaleUser implements UserStrategy
{
    function showAd(){
        echo "2016冬季女装";
    }
    function showCategory(){
        echo "女装";
    }
}
Copy after login
MaleUser.php
<?php require_once &#39;Loader.php&#39;;
class MaleUser implements UserStrategy
{
    function showAd(){
        echo "IPhone6s";
    }
    function showCategory(){
        echo "电子产品";
    }
}
Copy after login
Page.php//执行文件
strategy->showAd();
        echo "<br>";
        echo "Category";
        $this->strategy->showCategory();
        echo "<br>";
    }
    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();
Copy after login

执行结果图: 

What are the design patterns of php

What are the design patterns of php

 总结: <br>通过以上方式,可以发现,在不同用户登录时显示不同的内容,但是解决了在显示时的硬编码的问题。如果要增加一种策略,只需要增加一种策略实现类,然后在入口文件中执行判断,传入这个类即可。实现了解耦。 <br>实现依赖倒置和控制反转 (有待理解) <br>通过接口的方式,使得类和类之间不直接依赖。在使用该类的时候,才动态的传入该接口的一个实现类。如果要替换某个类,只需要提供一个实现了该接口的实现类,通过修改一行代码即可完成替换。

观察者模式

1:观察者模式(Observer),当一个对象状态发生变化时,依赖它的对象全部会收到通知,并自动更新。 <br>2:场景:一个事件发生后,要执行一连串更新操作。传统的编程方式,就是在事件的代码之后直接加入处理的逻辑。当更新的逻辑增多之后,代码会变得难以维护。这种方式是耦合的,侵入式的,增加新的逻辑需要修改事件的主体代码。 <br>3:观察者模式实现了低耦合,非侵入式的通知与更新机制。 

<br>定义一个事件触发抽象类。

EventGenerator.php
<?php require_once &#39;Loader.php&#39;;
abstract class EventGenerator{
    private $observers = array();
    function addObserver(Observer $observer){
        $this->observers[]=$observer;
    }
    function notify(){
        foreach ($this->observers as $observer){
            $observer->update();
        }
    }
}
Copy after login

定义一个观察者接口

Observer.php
<?php require_once &#39;Loader.php&#39;;
interface Observer{
    function update();//这里就是在事件发生后要执行的逻辑
}
Copy after login
addObserver(new Observer1());
$event->addObserver(new Observer2());
$event->triger();
$event->notify();
Copy after login

当某个事件发生后,需要执行的逻辑增多时,可以以松耦合的方式去增删逻辑。也就是代码中的红色部分,只需要定义一个实现了观察者接口的类,实现复杂的逻辑,然后在红色的部分加上一行代码即可。这样实现了低耦合。

原型模式

原型模式(对象克隆以避免创建对象时的消耗) <br>1:与工厂模式类似,都是用来创建对象。 <br>2:与工厂模式的实现不同,原型模式是先创建好一个原型对象,然后通过clone原型对象来创建新的对象。这样就免去了类创建时重复的初始化操作。 <br>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 "<br>;";
        }
    }
}
Copy after login
Index.php
init();
/ $canvas1 = new Canvas();
// $canvas1->init();
$canvas1 = clone $c;//通过克隆,可以省去init()方法,这个方法循环两百次
//去产生一个数组。当项目中需要产生很多的这样的对象时,就会new很多的对象,那样
//是非常消耗性能的。
$canvas1->rect(2, 2, 8, 8);
$canvas1->draw();
echo "-----------------------------------------<br>";
// $canvas2 = new Canvas();
// $canvas2->init();
$canvas2 = clone $c;
$canvas2->rect(1, 4, 8, 8);
$canvas2->draw();
Copy after login

执行结果:

What are the design patterns of php

装饰器模式

1:装饰器模式,可以动态的添加修改类的功能 <br>2:一个类提供了一项功能,如果要在修改并添加额外的功能,传统的编程模式,需要写一个子类继承它,并重写实现类的方法 <br>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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!