装饰器模式:某个类A,开发者用一个装饰器类将A作为属性引入到.m文件中,将A类的API重写,但是调用还是通过A的实例对象调用API。
这样做的好处就是可以更好的保护类A,外部开发者不会直接调用A类的API。
IOS中还有一个和装饰器模式很类似的机制就是分类Category。
但是分类和装饰器还是有差别的,当category重写该类的方法是,就算没有应用也是会执行该方法。而且在重写该方法是会有warning。
Category is implementing a method which will also be implemented by its primary class
GamePad类
#import <Foundation/Foundation.h>
@interface GamePad : NSObject
/**
* 上下左右的操作
*/
- (void)up;
- (void)down;
- (void)left;
- (void)right;
/**
* 选择与开始的操作
*/
- (void)select;
- (void)start;
/**
* 按钮 A + B + X + Y
*/
- (void)commandA;
- (void)commandB;
- (void)commandX;
- (void)commandY;
@end
#import "GamePad.h"
@implementation GamePad
- (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");
}
- (void)commandX {
NSLog(@"commandX");
}
- (void)commandY {
NSLog(@"commandY");
}
装饰类GamePadDecorator
#import <Foundation/Foundation.h>
@interface GamePadDecorator : NSObject
/**
* 上下左右的操作
*/
- (void)up;
- (void)down;
- (void)left;
- (void)right;
/**
* 选择与开始的操作
*/
- (void)select;
- (void)start;
/**
* 按钮 A + B + X + Y
*/
- (void)commandA;
- (void)commandB;
- (void)commandX;
- (void)commandY;
@end
#import "GamePadDecorator.h"
#import "GamePad.h"
@interface GamePadDecorator ()
@property (nonatomic, strong) GamePad *gamePad;
@end
@implementation GamePadDecorator
- (instancetype)init {
self = [super init];
if (self) {
self.gamePad = [[GamePad alloc] init];
}
return self;
}
- (void)up {
[self.gamePad up];
}
- (void)down {
[self.gamePad down];
}
- (void)left {
[self.gamePad left];
}
- (void)right {
[self.gamePad right];
}
- (void)select {
[self.gamePad select];
}
- (void)start {
[self.gamePad start];
}
- (void)commandA {
[self.gamePad commandA];
}
- (void)commandB {
[self.gamePad commandB];
}
- (void)commandX {
[self.gamePad commandX];
}
- (void)commandY {
[self.gamePad commandY];
}
@end
分类GamePad+Cheat
#import "GamePad.h"
@interface GamePad (Cheat)
- (void)cheat;
千万不用重写方法
//- (void)up;
@end
import "GamePad+Cheat.h"
@implementation GamePad (Cheat)
- (void)cheat {
[self up];
[self down];
[self up];
[self down];
[self left];
[self right];
[self left];
[self right];
[self commandA];
[self commandB];
[self commandA];
[self commandB];
}
//- (void)up {
// NSLog(@"1234536478965432");
//}
@end