iOS设计模式解析(三)适配器模式

  • 适配器模式:将一个类的借口转换成客户端希望的另一个接口
  • 有一个很直观的图:  
  • 例如      :电源适配器(将110V电压转换成220V电压,其中Traget是220V电压,adaptee就是110V电压,Adapter就是适配器):  
  • 代码实现
    1 #import "Adapter.h"
    2 
    3 @implementation Adapter
    4 -(int)changeTo220:(int)adaptee{
    5     return 220;
    6 }
    7 @end
    Adapter
     1 #import "ViewController.h"
     2 #import "Adapter.h"
     3 @interface ViewController ()
     4 
     5 @end
     6 
     7 @implementation ViewController
     8 
     9 - (void)viewDidLoad {
    10     [super viewDidLoad];
    11     
    12     int current       = 110;
    13     Adapter * adapter = [[Adapter alloc]init];
    14     int new           = [adapter changeTo220:110];
    15     NSLog(@"%d",new);
    16     
    17 }
    18 
    19 - (void)didReceiveMemoryWarning {
    20     [super didReceiveMemoryWarning];
    21 }
    22 
    23 @end
    ViewController
  • 打印结果

    2016-05-09 16:46:26.262 Factory[2766:204337] 220

  • 延伸总结:为什么说委托模式其实是适配器模式。其实Objecct-C中协议的概念就是定义一些外界可用的接口,那么外界需要用的值本类中的格式不一致。那么我们是不是可以在本类中声明一些接口,然后在本类接口中将外界需要的值我组织适配好通过声明的接口(协议)来传给外界。所以这么看来委托模式其实是适配器模式。
posted @ 2016-05-09 16:58  conor  阅读(224)  评论(0编辑  收藏  举报