适配器模式

适配器模式:将原来不能够在一起工作的类变得能在一起工作
类适配器:通过实现接口和继承实现


对象适配器:通过实现和组合实现

 

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;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值