概念
装饰模式是在不必改变原类文件和使用继承的情况下,动态地扩展一个对象的功能。它是通过创建一个包装对象,也就是装饰来包裹真实的对象.
UML
UML分析
Component(标准的装饰模式抽象类),它声明了一些操作,它具体的类讲进行重载以实现自己特定的操作。这个Component具体类是模式中的被装饰者,Component父类可以被细化为另一个叫做Decorator的抽象类,即装饰者抽象类。Decorator类中包含了一个Component的引用。Decorator的具体类为Component或者Decorator定义了几个扩展行为,并且会在自己的操作中内嵌Component操作。
案例
*GameDecortor
#import <Foundation/Foundation.h>
#import "ComponentGame.h"
@interface GameDecortor : NSObject
// 上下左右
- (void)up;
- (void)down;
- (void)left;
- (void)right;
// 选择与开始的操作
- (void)select;
- (void)start;
// 按钮
- (void)commandA;
- (void)commandB;
- (void)commandC;
- (void)commandD;
@end
- CheatGameDecotor
#import "GameDecortor.h"
@interface CheatGameDecotor : GameDecortor
// 作弊器
- (void)cheat;
@end
#import "CheatGameDecotor.h"
@implementation CheatGameDecotor
- (void)cheat {
// 作弊操作
[self up];
[self up];
[self down];
[self down];
[self commandA];
[self commandA];
}
@end
- ComponentGame
#import <Foundation/Foundation.h>
@interface ComponentGame : NSObject
// 上下左右
- (void)up;
- (void)down;
- (void)left;
- (void)right;
// 选择与开始的操作
- (void)select;
- (void)start;
// 按钮
- (void)commandA;
- (void)commandB;
- (void)commandC;
- (void)commandD;
@end
#import "GameDecortor.h"
#import "ComponentGame.h"
@interface GameDecortor ()
@property (nonatomic, strong)ComponentGame *game;
@end
@implementation GameDecortor
- (instancetype)init
{
self = [super init ];
if (self) {
self.game = [ComponentGame new];
}
return self;
}
// GameLoL里面所有的方法
- (void)up {
[self.game up];
}
- (void)down {
[self.game down];
}
- (void)left {
[self.game left];
}
- (void)right {
[self.game right];
}
- (void)select {
[self.game select];
}
- (void)start {
[self.game start];
}
- (void)commandA {
[self.game commandA];
}
- (void)commandB {
[self.game commandB];
}
- (void)commandC
{
[self.game commandC];
}
- (void)commandD
{
[self.game commandD];
}
@end
*ComponentGame类
#import <Foundation/Foundation.h>
@interface ComponentGame : NSObject
// 上下左右
- (void)up;
- (void)down;
- (void)left;
- (void)right;
// 选择与开始的操作
- (void)select;
- (void)start;
// 按钮
- (void)commandA;
- (void)commandB;
- (void)commandC;
- (void)commandD;
@end
#import "ComponentGame.h"
@implementation ComponentGame
- (void)up {
NSLog(@"up");
}
- (void)down {
NSLog(@"down");
}
- (void)left {
NSLog(@"left");
}
- (void)right {
NSLog(@"right");
}
@end
- ComponentGame (Cheat)
#import "ComponentGame.h"
@interface ComponentGame (Cheat)
- (void)cheat;
@property (nonatomic, copy)NSString *coin;
@end
#import "ComponentGame+Cheat.h"
#import <objc/runtime.h>
static const NSString *coinStr = @"coinStr";
@implementation ComponentGame (Cheat)
- (void)cheat {
// 作弊操作
[self up];
[self up];
[self down];
[self down];
[self commandA];
[self commandA];
}
- (void)setCoin:(NSString *)coin
{
objc_setAssociatedObject(self, (__bridge const void *)coinStr, coin, OBJC_ASSOCIATION_ASSIGN);
}
- (NSString *)coin
{
NSString *coins = objc_getAssociatedObject(self, (__bridge const void *)coinStr);
return coins;
}
@end
Demo