Obj-C 实现设计模式 -- Adapter

关于什么是适配器,一张图足以说明。

现在实现一下简单的适配器模式。现有的系统是WildTurkey,封装的目标厂商类是Duck。

分别看看这两者

WildTurkey

@protocol TurkeyProtocol <NSObject>
@required
- (void) gobble;
- (void) fly;
@end

@interface WildTurkey : NSObject <TurkeyProtocol>{
    
}
- (void) gobble;
- (void) fly;
@end

@implementation WildTurkey
- (void) gobble{
    NSLog(@"Gobble gobble"); 
}

- (void) fly{
    NSLog(@"short flying distance");
}
@end

Duck

@protocol DuckProtocol <NSObject>
@required
- (void) quack;
- (void) fly;
@end

@interface MallardDuck : NSObject <DuckProtocol>{
    
}
- (void) quack;
- (void) fly;
@end

@implementation MallardDuck

- (void) quack{
    NSLog(@"Duck Quack");
}

- (void) fly{
    NSLog(@"Duck flying");
}
@end

最关键的,适配器如何对应两者的接口。

#import "DuckProtocol.h"
#import "TurkeyProtocol.h"
@interface TurkeyAdapter : NSObject <DuckProtocol>{
    id<TurkeyProtocol> _turkey;
}
- (id)initWithTurkey:(id<TurkeyProtocol>)turkey;
@end

@implementation TurkeyAdapter
- (id)initWithTurkey:(id<TurkeyProtocol>)turkey{
    self = [super init];
    if (self) {
        _turkey = turkey;
    }
    return self;
}

- (void)quack{
    [_turkey gobble];
}

- (void)fly{
    for (int i = 0; i < 5; ++i) {
        [_turkey fly];
    }
}
@end

调用的时候用适配器进行封装,就直接可以调用对应的Duck的方法。

WildTurkey * turkey = [[WildTurkey alloc] init];
TurkeyAdapter * tkAdapter = [[TurkeyAdapter alloc] initWithTurkey:turkey];
[tkAdapter fly];
posted @ 2012-05-04 00:19  Andy Wang  阅读(184)  评论(0编辑  收藏  举报