标签:
iOS设计模式 - 装饰
原理图
说明
1. cocoa框架本身实现了装饰模式(category的方式实现了装饰模式)
2. 装饰模式指的是动态的给一个对象添加一些额外的职责,相对于继承子类来说,装饰模式更加灵活
*3. 本人仅仅实现了最简单的装饰模式,装饰器类是一个具体的类,非抽象类
源码
https://github.com/YouXianMing/DecoratorPattern
// // GamePlay.h // DecoratorPattern // // Created by YouXianMing on 15/8/1. // Copyright (c) 2015年 YouXianMing. All rights reserved. // #import <Foundation/Foundation.h> @interface GamePlay : NSObject /** * 游戏币的数量 */ @property (nonatomic) NSInteger coin; /** * 上下左右的操作 */ - (void)up; - (void)down; - (void)left; - (void)right; /** * 选择与开始的操作 */ - (void)select; - (void)start; /** * 按钮 A + B 的操作 */ - (void)commandA; - (void)commandB; @end
// // GamePlay.m // DecoratorPattern // // Created by YouXianMing on 15/8/1. // Copyright (c) 2015年 YouXianMing. All rights reserved. // #import "GamePlay.h" @implementation GamePlay - (void)up { NSLog(@"up"); } - (void)down { NSLog(@"down"); } - (void)left { NSLog(@"left"); } - (void)right { NSLog(@"right"); } - (void)select { NSLog(@"select"); } - (void)start { NSLog(@"start"); } - (void)commandA { NSLog(@"commandA"); } - (void)commandB { NSLog(@"commandB"); } @end
// // DecoratorGamePlay.h // DecoratorPattern // // Created by YouXianMing on 15/8/1. // Copyright (c) 2015年 YouXianMing. All rights reserved. // #import <Foundation/Foundation.h> #import "GamePlay.h" @interface DecoratorGamePlay : NSObject @property (nonatomic) NSInteger coin; - (void)up; - (void)down; - (void)left; - (void)right; - (void)select; - (void)start; - (void)commandA; - (void)commandB; #pragma mark - 以下为装饰对象新添加的功能 /** * 剩余几条命 */ @property (nonatomic, readonly) NSInteger lives; /** * 作弊 (上下上下左右左右ABAB) */ - (void)cheat; @end
// // DecoratorGamePlay.m // DecoratorPattern // // Created by YouXianMing on 15/8/1. // Copyright (c) 2015年 YouXianMing. All rights reserved. // #import "DecoratorGamePlay.h" @interface DecoratorGamePlay () @property (nonatomic, strong) GamePlay *gamePlay; @end @implementation DecoratorGamePlay #pragma mark - 初始化 - (instancetype)init { self = [super init]; if (self) { // 装饰对象包含一个真实对象的引用 self.gamePlay = [GamePlay new]; } return self; } #pragma mark - 让真实对象的引用执行对应的方法 - (void)up { [_gamePlay up]; } - (void)down { [_gamePlay down]; } - (void)left { [_gamePlay left]; } - (void)right { [_gamePlay right]; } - (void)select { [_gamePlay select]; } - (void)start { [_gamePlay start]; } - (void)commandA { [_gamePlay commandA]; } - (void)commandB { [_gamePlay commandB]; } #pragma mark - 装饰器新添加的方法 - (void)cheat { [_gamePlay up]; [_gamePlay down]; [_gamePlay up]; [_gamePlay down]; [_gamePlay left]; [_gamePlay right]; [_gamePlay left]; [_gamePlay right]; [_gamePlay commandA]; [_gamePlay commandB]; [_gamePlay commandA]; [_gamePlay commandB]; } @synthesize lives = _lives; - (NSInteger)lives { // 相关处理逻辑 return 10; } @end
分析
以下是装饰模式实现细节对照图
标签:
原文地址:http://www.cnblogs.com/YouXianMing/p/4693606.html