设计模式----适配器模式

    适配器模式(Adapter):将一个接口转换成客户希望的另一个接口,适配器模式使接口不兼容的那些类可以一起工作,其别名为包装器(Wrapper)。适配器模式既可以作为类结构型模式,也可以作为对象结构型模式。

     适配器模式的优点:将目标类和适配者类解耦,通过引入一个适配器类来重用现有的适配者类,而无须修改原有代码。增加了类的透明性和复用性,将具体的实现封装在适配者类中,对于客户端类来说是透明的,而且提高了适配者的复用性。灵活性和扩展性都非常好,通过使用配置文件,可以很方便地更换适配器,也可以在不修改原有代码的基础上增加新的适配器类,完全符合“开闭原则”。

    具体实例:一个软件团队开发绘图系统,设计了圆对象(Circle)、矩形对象(Rectangle),线对象(Line)都支持Draw()函数,即可以通过Draw()函数绘制图形。为了加快项目进度,将角度对象(Angle)绘制功能交给了合作团队实现。但合作团队将角度对象绘制函数定为了DrawAngle()。绘图系统提供给用户后,用户不满意,希望能统一的调用,不用记太多命令。应用适配器模式,完善该设计。

#include<iostream>
#include<string>
using namespace std;
class Picture
{ 
  public:
	string type;
    Picture(string name)
    {
        type=name;
    }
    virtual void Draw(){};
};
//圆对象
class Circle:public Picture
{
public:
    Circle(string name):Picture(name)
    {  }
	
    virtual void Draw()
    {
        cout<<type<<endl;
		cout<<"绘制圆形"<<endl;
    }
};
//矩形对象
class Rectangle:public Picture
{
public:
    Rectangle(string name):Picture(name)
    {}
    virtual void Draw()
    {
        cout<<type<<endl;
		cout<<"绘制矩形"<<endl;
    }
};
//线对象
class Line:public Picture
{
public:
    Line(string name):Picture(name)
    {}
    virtual void Draw()
    {
        cout<<type<<endl;
		cout<<"绘制线"<<endl;
    }
};
//角度对象
class Angle
{
private:
    string type;
public:
    void SetType(string name)
    {
        type=name;
    }
    string GetType()
    {
        return type;
    }
    void DrawAngle()
    {
        
		cout<<"绘制角度"<<endl;
    }
};
//翻译类
class Translator:public Picture
{
private:
    Angle Drawangle;
public:
    Translator(string name):Picture(name)
    {
		Drawangle.SetType(name);
    }
    virtual void Draw()
    {
		cout<<type<<endl;
		cout<<Drawangle.GetType()<<endl;
		Drawangle.DrawAngle();
    } 
};
int main()
{
    Picture *circle = new Circle("圆形");
	Picture *rectangle = new Rectangle("矩形");
	Picture *line = new Line("直线");
	Picture *translator = new Translator("角度");
	circle->Draw();
	rectangle->Draw();
	line->Draw();
	translator->Draw();
	system("pause");
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值