适配器模式:将原来不能够在一起工作的类变得能在一起工作
类适配器:通过实现接口和继承实现
对象适配器:通过实现和组合实现
1、iPhone 6 充电电压5V,插座电压220V 手机通过电源适配器直接能够用上
目标电压5V,220V电压作为适配者(Adaptee)。
2、Objective-C 中协议充当Target需要被实现,UIViewController充当适配者,
如何让协议和UIViewController进行通信,这时候需要自定义视图控制作为适配器
让协议和UIViewController能够在一起工作。
3、Objective-C 块是适配器模式的具体实现,让两个不同的模块可以在一起工作:
应用场景: 块在视图控制器中声明,让块能过捕获UI控件,同时将块作为参数传入
到其他模块其他模块copy块,在任何时候,这样其他模块能够捕获到UI控件中最新的数据
4、Cocoa Touch框架中的委托(delegate)对应对象适配器,Target对应
委托协议,实现委托协议是个具体的类,这个类就是对象适配器,应用中组合其他
类作为适配者(Adaptee)
类适配器:
#import <iostream>
using namespace std;
class ITarget{
public:
virtual void target() = 0;
};
class Adaptee{
public:
void doSomething(){
std::cout << "do something" <<std::endl;
}
};
class Adapter: public ITarget,public Adaptee{
public:
void target(){
doSomething();
}
};
int main(int argc, const char * argv[]) {
ITarget* target = new Adapter();
target -> target();
return 0;
}
对象适配器:
#import <iostream>
using namespace std;
class ITarget{
public:
virtual void target() = 0;
};
class Adaptee{
public:
void doSomething(){
std::cout << "do something" <<std::endl;
}
};
class Adapter: public ITarget{
private:
Adaptee* mAdaptee;
public:
Adapter(Adaptee* adaptee):mAdaptee(adaptee){}
void target(){
mAdaptee -> doSomething();
}
};
int main(int argc, const char * argv[]) {
ITarget* target = new Adapter(new Adaptee);
target -> target();
return 0;
}