iOS设计模式 (五) 适配器模式
2018-05-12 本文已影响9人
handsome5
适配器模式
- iOS中的适配器模式,主要由目标协议,适配者,适配器三部分组成.
适配器模式分类
- 类适配器: 适配器是继承自适配者的
- 对象适配器 : 适配器是引用适配者的
适配器模式UML
5.png适配器模式实例应用
- USD类
#import <Foundation/Foundation.h>
@interface USD : NSObject
- (float)accepteUSD;
@end
#import "USD.h"
@implementation USD
- (float)accepteUSD
{
return 100;
}
@end
- AcepptDapter类(目标协议)
#import <Foundation/Foundation.h>
@protocol AcepptDapter <NSObject>
- (float)dapterUSD;
@end
- DapaterRMB 类
#import "USD.h"
#import "AcepptDapter.h"
@interface DapaterRMB : USD<AcepptDapter>
@end
#import "DapaterRMB.h"
@implementation DapaterRMB
- (float)dapterUSD
{
return [self accepteUSD] *6.61;
}
@end
- ViewController类
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
@end
#import "ViewController.h"
#import "DapaterRMB.h"
#import "ObjectDapterCNY.h"
#import "USD.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
DapaterRMB *dapterRMB = [[DapaterRMB alloc] init];
float dd = [dapterRMB dapterUSD];
NSLog(@"ddd ====== :%0.2f",dd);
ObjectDapterCNY *cny = [[ObjectDapterCNY alloc] initWithObject:[USD new]];
float cc = [cny dapterUSD];
NSLog(@"cc =====:%0.2f",cc);
}
@end
- ObjectDapterCNY (对象适配者)
#import <Foundation/Foundation.h>
#import "USD.h"
#import "AcepptDapter.h"
@interface ObjectDapterCNY : NSObject<AcepptDapter>
@property (nonatomic, strong)USD *usdDapter;
- (instancetype)initWithObject:(USD *)dapterUSD;
@end
#import "ObjectDapterCNY.h"
@implementation ObjectDapterCNY
- (instancetype)initWithObject:(USD *)dapterUSD
{
self = [super init];
if (self) {
self.usdDapter = dapterUSD;
}
return self;
}
- (float)dapterUSD
{
return [self.usdDapter accepteUSD] *6.61;
}
@end
- 很简单的入门适配器模式,但是真正的适配器在开发过程中很常用。
- TableView适配器demo地址:https://github.com/defuliu/DapterPattern.git 觉得不错的话,请打个star.
- 思考点: 桥接模式跟适配器模式有什么区别呢?