设计模式(二结构型模式)

2020-04-30  本文已影响0人  X1_blog

适配器模式

目的

增加兼容性, 调和两个接口; 属于接口再封装

类型

类适配器 / 对象适配器

优点

  1. 接口变动时, 改适配器就可以继续工作, 灵活性增强
  2. 不影响源类本身的工作
  3. 适配器模式下实现了php多继承

使用场景

  1. 稳定接口需要修改功能时, 为了避免违背开闭原则, 应当使用适配器模式进行改动; 只要确保适配器测试正常就不用担心影响源接口功能

DEMO

/*类适配器模式*/
interface Target{
    function method_1();
}


class Adaptee 
{
    function method_2()
    {
        echo "method_2";
    }
}
 

class Adapter extends Adaptee implements Target
{
    function method_1()
    {
        echo "method_1";
    }
}


class client
{
    
    static function test()
    {
        $adapter = new Adapter();
        $adapter -> method_1();
        $adapter -> method_2();
    }
}

client::test();
/*对象适配器*/
interface Target{
    function method_1();
}

class Adaptee 
{
    function method_2()
    {
        echo "method_2";
    }
}
 
class Adapter implements Target
{
    private $adaptee ;
    public function __construct(Adaptee $adaptee)
    {
        $this->adaptee = $adaptee;
    }
    function method_1()
    {
        echo "method_1";
    }

    function method_2()
    {
        $this->adaptee -> method_2();
    }
}


class client
{
    static function test()
    {
        $adaptee = new Adaptee();
        $adapter = new Adapter($adaptee);
        $adapter -> method_1();
        $adapter -> method_2();
    }
}

client::test();

装饰器模式

组成

装饰模式包含如下角色:

目的

创建装饰类对被装饰类的属性/方法进行运算/调整, 且不影响被装饰类的结构(属性/方法)

实现方法

将被装饰类的实例作为装饰类的参数传入, 在装饰类上添加新的方法

/*装饰器模式*/
class Component
{
    public $userList = ["mary","tom"];
    function show()
    {
        print_r($this->userList);
    }
}


class Decorator 
{
    private $component ;
    function __construct(Component $component){
        $this->component = $component ;
    }
    function uppercase()
    {
        foreach ($this->component->userList as $key => $value) {
            $this->component->userList[$key] = strtoupper($value);
        }
    }
}

$component = new Component();
$decorator = new Decorator($component);
$decorator-> uppercase();
$component-> show();

代理模式

定义

创建代理类, 拥有被代理类(真实类)的部分/全部同名方法, 客户端通过调用代理类使用真实类的方法

使用场景

  1. 隐藏真实类
  2. 创建多个代理类对不同调用者进行权限管理
  3. 在代理类中实现功能的简单扩展(不提倡)

DEMO

/*代理模式*/
interface shopping{
    function buy();
}
/*代理类*/
class proxyShopping implements shopping
{
    private $realShopping ;
    function buy()
    {
        $this->say();
        if(!$this->realShopping)$this->realShopping = new realShopping();
        $this->realShopping->buy();
    }
    function say(){
        echo "proxy start\n";
    }
}

/*真实类*/
class realShopping implements shopping
{
    
    function buy()
    {
        echo "buy something...";
    }
}

class client
{
    /*客户端只知道代理类存在, 从而保护了真实类*/
    static function main()
    {
        $shopping = new proxyShopping();
        $shopping->buy();
    }
}
client::main();
上一篇下一篇

猜你喜欢

热点阅读