设计模式之适配器模式,golang,php实现

程序员卷不动了 2023-03-18 PM 391℃ 0条

适配器模式是一种结构型设计模式。它的主要目的是将一种接口转换成客户希望的另一种接口表示。适配器使原本由于接口不兼容而无法工作的类能够一起工作。

适配器模式中通常有三个主要角色:

  1. 目标接口(Target):客户端所希望的接口。
  2. 源接口(Adaptee):需要被适配的接口。
  3. 适配器(Adapter):将源接口转换成目标接口的类。

适配器模式可以使用两种不同的实现方法:

  1. 类适配器:使用继承来适配接口,即适配器实现目标接口,同时继承源接口,实现目标接口的方法调用源接口的方法。
  2. 对象适配器:使用组合来适配接口,即适配器实现目标接口,同时包含了一个源接口的实例,目标接口的方法调用源接口实例的方法。

适配器模式的优点在于可以通过适配器将不兼容的接口组合在一起,为客户端提供更加便利的接口访问。缺点在于如果要适配多个接口,则需要定义多个适配器类,代码复杂度可能会增加。

golang实现代码:

// 目标接口
type Target interface {
    Request() string
}

// 源接口
type Adaptee interface {
    SpecificRequest() string
}

// 源接口实现
type ConcreteAdaptee struct {}

func (a *ConcreteAdaptee) SpecificRequest() string {
    return "SpecificRequest"
}

// 适配器
type Adapter struct {
    adaptee Adaptee
}

func NewAdapter(adaptee Adaptee) *Adapter {
    return &Adapter{adaptee: adaptee}
}

func (a *Adapter) Request() string {
    return a.adaptee.SpecificRequest()
}

// 测试代码
func main() {
    adaptee := &ConcreteAdaptee{}
    adapter := NewAdapter(adaptee)
    result := adapter.Request()
    fmt.Println(result) // Output: SpecificRequest
}

适配器实现了目标接口 Target 并包含源接口 Adaptee 的一个实例。通过调用适配器的 Request 方法,实际上是调用了适配器中实现的 SpecificRequest 方法来完成源接口的适配。

php实现代码:

// 目标接口
interface Target {
    public function request();
}

// 源接口
interface Adaptee {
    public function specificRequest();
}

// 源接口实现
class ConcreteAdaptee implements Adaptee {
    public function specificRequest() {
        return 'SpecificRequest';
    }
}

// 适配器
class Adapter implements Target {
    protected $adaptee;

    public function __construct(Adaptee $adaptee) {
        $this->adaptee = $adaptee;
    }

    public function request() {
        return $this->adaptee->specificRequest();
    }
}

// 测试代码
$adaptee = new ConcreteAdaptee();
$adapter = new Adapter($adaptee);
$result = $adapter->request();
echo $result; // Output: SpecificRequest

适配器 Adapter 实现了目标接口 Target 并包含源接口 Adaptee 的一个实例。通过调用适配器的 request 方法,实际上是调用了适配器中实现的 specificRequest 方法来完成源接口的适配。

标签: 设计模式

非特殊说明,本博所有文章均为博主原创。

评论啦~