今天准备和大家分享一下使用Objective C简单实现设计模式里的装饰模式。
首先,简单介绍一下装饰模式(Decorator)。
装饰模式(Decorator),动态地给一个对象添加一些额外地职责,就增加功能来说,装饰模式比生成子类更为灵活。装饰模式主要是为已有功能动态地添加更多功能的一种方式。当系统需要新功能的时候,是向旧的类中添加新的代码。这些新加的代码通常装饰了原有类的核心职责或主要行为。
下面我把类的结构图向大家展示如下:
让我们简单分析一下上面的结构图,Component是定义一个对象接口,可以给这些对象动态地添加职责。ConcreteComponent是定义了一个具体的对象,也可以给这个对象添加一些职责。Decorator,装饰抽象类,继承了Component,从外类来扩展Component类的功能,但对于Component来说,是无需知道Decorator的存在的。至于ConcreteDecorator就是具体的装饰对象,起到给Component添加职责的功能。
下面,还是老套路,我会尽可能的给出Objective C实现的最简单的实例代码,首先声明一下,这些代码是运行在ARC环境下的,所以对于某些可能引起内存泄漏的资源并没有采用手动释放的方式,这一点还是需要大家注意。
============================================
-
Components类接口文件
1
2
3
4
5
|
#import<Foundation/Foundation.h>
@interface
Components :
NSObject
-(
void
) Operation;
@end
|
-
Components类实现文件
1
2
3
4
5
6
7
|
#import"Components.h"
@implementation
Components
-(
void
)Operation{
return
;
}
@end
|
-
Decorator类接口文件
1
2
3
4
5
6
7
|
#import"Components.h"
@interface
Decorator :Components{
@protected
Components *components;
}
-(
void
)SetComponents:(Components*)component;
@end
|
-
Decorator类实现文件
1
2
3
4
5
6
7
8
9
10
11
12
|
#import"Decorator.h"
@implementation
Decorator
-(
void
)SetComponents:(Components*)component{
components = component;
}
-(
void
)Operation{
if
(components!=
nil
){
[components Operation];
}
}
@end
|
-
ConcreteComponent类接口文件
1
2
3
4
|
#import"Components.h"
@interface
ConcreteComponent:Components
@end
|
-
ConcreteComponent类实现文件
1
2
3
4
5
6
7
|
#import "ConcreteComponent.h"
@implementation
ConcreteComponent
-(
void
)Operation{
NSLog
(@
"具体操作的对象"
);
}
@end
|
-
ConcreteDecoratorA类接口文件
1
2
3
4
5
|
#import "ConcreteDecoratorA.h"
#import "Decorator.h"
@interface
ConcreteDecoratorA:Decorator
@end
|
-
ConcreteDecoratorA类实现文件
1
2
3
4
5
6
7
8
|
#import"ConcreteDecoratorA.h"
@implementation
ConcreteDecoratorA
-(
void
)Operation{
NSLog
(@
"具体装饰对象A的操作"
);
[
super
Operation];
}
@end
|
-
ConcreteDecoratorB类接口文件
1
2
3
4
|
#import "Decorator.h"
@interface
ConcreteDecoratorB:Decorator
@end
|
-
ConcreteDecoratorB类实现文件
1
2
3
4
5
6
7
8
|
#import "ConcreteDecoratorB.h"
@implementation
ConcreteDecoratorB
-(
void
)Operation{
NSLog
(@
"具体装饰对象B的操作"
);
[
super
Operation];
}
@end
|
-
Main方法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
#import <Foundation/Foundation.h>
#import "ConcreteComponent.h"
#import "ConcreteDecoratorA.h"
#import "ConcreteDecoratorB.h"
int
main (
int
argc,
const
char
* argv[])
{
@autoreleasepool
{
ConcreteComponent *c = [[ConcreteComponentalloc]init];
ConcreteDecoratorA *d1 = [[ConcreteDecoratorAalloc]init];
ConcreteDecoratorB *d2 = [[ConcreteDecoratorBalloc]init];
[d1 SetComponents:c];
[d2 SetComponents:d1];
[d2 Operation];
}
return
0;
}
|
好啦,上面是需要展示的类,语法上都很简单,没有什么需要重点说的,可能值得一提的是关于子类调用父类方法的知识点,就是在调用每个对象的Operation方法的时候,里面会有一句代码是[super Operation];这句代码构很关键,他构成了各个对象之间Operation方法的跳转,以此完成对Components类对象的"装饰"。
ok,上面就是今天要说的装饰模式。