设计模式——适配器模式

1、定义

将一个类的接口转换成客户期望的另一个接口。适配器让原本接口不兼容的类可以合作无间
一般分为对象适配器和类适配器

我喜欢的样子你都有
你喜欢的样子我有没有
没有的话,我送你个适配器,好吗

适配器模式是在现有的类和系统都不易修改的情况下使用,在系统设计之初慎用适配器模式。

2、对象适配器和类适配器的优缺点

类适配器的优点:

1、由于适配器类是适配者类的子类,因此可以再适配器类中置换一些适配者的方法,使得适配器的灵活性更强。

类适配器的缺点:

1、对于Java、C#等不支持多重继承的语言,一次最多只能适配一个适配者类,而且目标抽象类只能为接口,不能为类,其使用有一定的局限性,不能将一个适配者类和他的子类同时适配到目标接口。

对象适配器的优点:

1、把多个不同的适配者适配到同一个目标,也就是说,同一个适配器可以把适配者类和他的子类都适配到目标接口。

对象适配器的缺点:

1、与类适配器模式相比,要想置换适配者类的方法就不容易。

3、结构

类适配器

在这里插入图片描述
在这里插入图片描述

对象适配器

在这里插入图片描述

4、代码

#pragma once
//目标接口类,客户需要的接口
class Target
{
public:
    Target();
    virtual ~Target();
    virtual void Request();//定义标准接口
};

//需要适配的类
class Adaptee
{
public:
    Adaptee();
    ~Adaptee();
    void SpecificRequest();
};

//类模式,适配器类,通过public继承获得接口继承的效果,通过private继承获得实现继承的效果
class Adapter :public Target, private Adaptee
{
public:
    Adapter();
    ~Adapter();
    virtual void Request();//实现Target定义的Request接口
};

//对象模式,适配器类,继承Target类,采用组合的方式实现Adaptee的复用
class Adapter1 :public Target
{
public:
    Adapter1(Adaptee* adaptee);
    Adapter1();
    ~Adapter1();
    virtual void Request();//实现Target定义的Request接口
private:
    Adaptee* _adaptee;
};
#include "Adaptor.h"
#include <iostream>

using namespace std;

Target::Target()
{}

Target::~Target()
{}

void Target::Request()
{
    cout << "Target::Request()" << endl;
}

Adaptee::Adaptee()
{
}

Adaptee::~Adaptee()
{
}

void Adaptee::SpecificRequest()
{
    cout << "Adaptee::SpecificRequest()" << endl;
}

//类模式的Adapter
Adapter::Adapter()
{
}

Adapter::~Adapter()
{
}

void Adapter::Request()
{
    cout << "Adapter::Request()" << endl;
    this->SpecificRequest();
    cout << "----------------------------" << endl;
}

//对象模式的Adapter
Adapter1::Adapter1() :_adaptee(new Adaptee)
{
}

Adapter1::Adapter1(Adaptee* _adaptee)
{
    this->_adaptee = _adaptee;
}

Adapter1::~Adapter1()
{
}

void Adapter1::Request()
{
    cout << "Adapter1::Request()" << endl;
    this->_adaptee->SpecificRequest();
    cout << "----------------------------" << endl;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值