【php设计模式】适配器模式

时间:2022-06-22
本文章向大家介绍【php设计模式】适配器模式,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

适配器模式(对象适配器、类适配器): 

将一个类的接口转换成客户希望的另一个接口。适配器模式让那些接口不兼容的类可以一起工作。

  在适配器模式定义中所提及的接口是指广义的接口,它可以表示一个方法或者方法的集合。 角色: Target(目标抽象类)     目标抽象类定义客户所需的接口,可以是一个抽象类或接口,也可以是具体类。   Adapter(适配器类)     它可以调用另一个接口,作为一个转换器,对Adaptee和Target进行适配。它是适配器模式的核心。   Adaptee(适配者类)     适配者即被适配的角色,它定义了一个已经存在的接口,这个接口需要适配,适配者类包好了客户希望的业务方法。

对象适配器:

interface Target{
    public function MethodOne();
    public function MethodTwo();
}

class Adaptee{
    public function MethodOne(){
        echo "+++++++++n";
    }
}

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

    public function MethodOne(){
        $this->adaptee->MethodOne();
    }

    public function MethodTwo(){
        echo "------------";
    }
}

$adaptee = new Adaptee();
$adapter = new Adapter($adaptee);
$adapter->MethodOne();

类适配器:

class Adapter2 extends Adaptee implements Target{
    public function MethodTwo(){
        echo "-----------";
    }
}
$adapter2 = new Adapter2();
$adapter2->MethodOne();