适配器模式

7次阅读

共计 851 个字符,预计需要花费 3 分钟才能阅读完成。

简介

在面向过程的编程中,我们也经常会遇到接口不一致的情况,此时需要对原先的接口进行包装或适配。在面向对象中,适配器模式是指将一个类的接口转换成客户期望的接口,适配器模式让之前由于接口不兼容的类可以一起工作。它有两种方式,一种是类适配器,一种是对象适配器模式,我们只介绍对象适配器模式。

UML 类图

示例

宝钢和武钢合并成立宝武,这两家公司肯定需要有多个系统需要融合,在这里我们使用宝钢的系统,武钢的系统需要进行适配,我们简单抽象出宝钢系统类和武钢系统类。
适配器类(CAdapter),武钢系统的类(CWuSteelSystem),宝钢系统的类 (CBaoSteelSystem)

#ifndef ADAPTER_H
#define ADAPTER_H

using namespace std;
class CBaoSteelSystem
{
public:
    virtual void AddPerson(){}
};

class CWuSteelSystem
{
    public:
        long AddEmployee()
        {return 0;}
};

class CAdapter:public CBaoSteelSystem
{
public:    
    CAdapter(CWuSteelSystem *pSystem):m_pSystem(pSystem){}
    virtual void AddPerson()
    {m_pSystem->AddEmployee();
    }
public:
    CWuSteelSystem* m_pSystem;
};
#endif

客户端调用的类

#include "adapter.h"

#define SAFE_DELETE(p) if(p){delete (p); (p) = 0;}
int main()
{
    CWuSteelSystem* pSystem = new CWuSteelSystem;
    CAdapter* pAdater = new CAdapter(pSystem);
    pAdater->AddPerson();
    
    SAFE_DELETE(pAdater)
    SAFE_DELETE(pSystem)
}

正文完
 0

适配器模式

7次阅读

共计 1135 个字符,预计需要花费 3 分钟才能阅读完成。

适配器模式
定义

将一个接口转换成客户期望的另一个接口。这里的接口可以指一个接口也可以是一个类,一个方法。
使本来接口不兼容的类可以一起工作。

类型
结构型
使用场景

已经存在的类,他的方法和需求不匹配时(方法结果相同或相似)
适配器模式不是软件设计阶段考虑的设计模式,是随着软件维护不同的产品、不同厂家造成的功能相似接口不同的情况下的解决方案。

优点

能提高类的透明性和复用性,现有的类的服用但不需要改变。
目标类和适配器类解耦,提高程序的扩展性。
符合开闭原则

下面开始看代码, 首先我们来实现一下类适配器模式。先写一个待适配的类。
public class Adaptee {
public void adapteeRequest(){
System.out.println(“ 被适配者的方法 ”);
}

}
适配接口
public interface Target {
void request();
}
没有经过适配的接口的实现类
public class ConcreteTarget implements Target {
@Override
public void request() {
System.out.println(“concreteTarget 目标方法 ”);
}

}
适配器登场,适配器类继承了待适配的类,同时实现了适配接口,所以我们直接使用 super 调用父类方法即可。
public class Adapter extends Adaptee implements Target{
@Override
public void request() {
//… 业务逻辑
super.adapteeRequest();
//…
}
}

测试类
public class ClassadapterTest {
public static void main(String[] args) {
Target target = new ConcreteTarget();
target.request();

Target adapterTarget = new Adapter();
adapterTarget.request();

}
}
运行结果
concreteTarget 目标方法
被适配者的方法
我们下面实现一下使用对象组合的方式类实现适配模式,一般情况下我们推荐使用对象组合的方式来实现适配器模式。在使用对象组合的方式我们的待适配类的和适配接口以及原来的接口实现类都是一样的唯一需要改变的就是适配类。
public class Adapter implements Target{
private Adaptee adaptee = new Adaptee();

@Override
public void request() {
//…
adaptee.adapteeRequest();
//…
}
}
这里的话使用带适配的类的对象来调用带适配的方法。

正文完
 0