结构型模式:适配器模式

来源:互联网 发布:淘宝怎么心极多点 编辑:程序博客网 时间:2024/05/16 05:31

意图:将一个类的接口转换成客户希望的另一种接口,从而使原本接口不兼容而无法在一起工作的那些类能够在一起工作。

适配器模式分为:类适配器模式对象适配器模式

类适配器模式


客户端需要实现SpecificRequest()操作,但是需要Request()方法,为了使客户能够使用Adaptee类,提供一个中间环节(Adapter类),Adapter继承自AdapteeAdapter类的Request方法重新封装了AdapteeSpecificRequest方法,实现了适配的目的。

对象适配器模式


客户端需要实现SpecificRequest()操作,但是需要Request()方法,为了使客户端能够使用Adaptee类,提供一个中间环节(Adapter类),这个类包装了一个Adaptee的实例,从而将客户端与Adaptee衔接起来。

类适配器模式C++实现

#include<iostream>    using namespace std;            class Target  {    public:        virtual void Request(){};    };            class Adaptee  {    public:        void SpecificRequest()        {            cout<<"Called SpecificRequest()"<<endl;        }    };            class Adapter : public Adaptee, public Target  {    public:        void Request()        {              this->SpecificRequest();        }    };                    int main()    {          Target *t = new Adapter();         t->Request();         return 0;    }

对象适配器模式C++实现

#include<iostream>  using namespace std;        class Target{  public:      virtual void Request(){};  };        class Adaptee  {  public:      void SpecificRequest()      {          cout<<"Called SpecificRequest()"<<endl;      }  };        class Adapter : public Target{  private:      Adaptee *adaptee;      public:      Adapter()      {          adaptee = new Adaptee();      }            void Request()      {          adaptee->SpecificRequest();      }  };         int main()  {       Target *t = new Adapter();       t->Request();       return 0;  }  

0 0
原创粉丝点击