设计模式之适配器

设计模式分为创建型模式,结构型模式,行为模式。

结构型模式主要讲的十如何组合类和对象的关系以获得更大的结构,结构性模式一般会利用继承的机制来组合接口或者实现,适配器使得一个接口与其他接口的兼容,从而使得多个不同的接口统一的抽象。

适配器(Adapter)为类对象结构型的一种设计模式,意图是将原本不一致的接口不兼容的类可以一起工作,适用于的场景如下:

1、想使用一个存在的类,但是它的接口不符合规范

2、想要创建一个可以复用的类,该类可以与其他不想关的类或不可预见的类进行协同工作。

3、想要使用已经存在的子类,但是不能每一个都进行子类化,所以可以适配它的父类。

 

外部的程序调用Target 类的接口,在adaptee里面完成具体的实现,Adapter是完成适配的操作接口。

实现方式主要有两种:

1、一种是Adapter继承Target 和 adaptee的实现

2、Adaptee实例作为Adapter的组成部分。

 

角色介绍

参与者

target:

定义client使用的与特定领域的相关的接口

client:

调用方,与符合Target接口的对象协同

adaptee:

定义一个已经存在的接口,这个接口需要适配。

adapter:

对adapter的接口与Target接口进行适配。

类适配代码

class Shape{
public:
    Shape(){
     cout<<"shape construct"<<endl
     } 
     virtual void BondingBox(){
     cout<<"hhhhh"<<endl;
     }
     
     virtual void Mainpulator()
     {
      cout<<"main"<<endl;
     }

};

class TextView{
public:
    TextView(){
     cout<<"text view construct"<<endl;
    } 
    void get_content()
    {
       cout<<"text view"<<endl;
    }

    void getnetx()
   {
      cout<<"getnetx"<<endl;
    }

};

class TextShape:public Shape,private TextView
{
public:
    TextShape()
    {
     cout<<"textshape construct"<<endl;
    }
    
     virtual void BondingBox(){
         get_content();
     }
     
     virtual void Mainpulator()
     {
          getnetx();
     }
 
}; //this is class  Adapter

 

对象适配代码

class Shape{
public:
    Shape(){
     cout<<"shape construct"<<endl
     } 
     virtual void BondingBox(){
     cout<<"hhhhh"<<endl;
     }
     
     virtual void Mainpulator()
     {
      cout<<"main"<<endl;
     }

};

class TextView{
public:
    TextView(){
     cout<<"text view construct"<<endl;
    } 
    void get_content()
    {
       cout<<"text view"<<endl;
    }

    void getnetx()
   {
      cout<<"getnetx"<<endl;
    }

};

class TextShape:public Shape
{
public:
    TextShape()
    {
        t = new TextView();
        cout<<"textshape construct"<<endl;
    }
    
     virtual void BondingBox(){
          t->get_content();
     }
     
     virtual void Mainpulator()
     {
           t->getnetx();
     }
paivate:
    TextView *t;
 
}; //这个是对象适配

 

优缺点总结

类适配器
1、当想要匹配一个类以及它的所有子类时,不可。(缺点)

2、可以用adapter重新定义adaptee的部分行为,因为adapter是adaptee的子类(优点)

3、仅仅利用了一个对象,不需要额外的指针就能够得到adaptee。(优点)

对象适配器:

1、优点允许一个adapter 适配多个adaptee(因为adaptee作为一个成员在里面),支持它们同时工作,Adapter可以一次给所有的adaptee添加功能。(优点)

2、重定义adaptee的行为比较困难,需要生成adaptee的子类,然后用adapter引用这个子类而不是引用adaptee本身。

 

综上所述,就是adapter的设计模式。

 

posted @ 2017-11-28 17:39  zhangjingle  阅读(182)  评论(0)    收藏  举报