今天想和大家分享的是命令模式。下面还和之前一样,先给出基本的定义。
命令模式(Command),将一个请求封装为一个对象,从而使你可用不同的请求对客户进行参数化;对请求排队或纪录请求日志,以及支持可撤销的操作。
那么让我们简要的说一下命令模式的特点。
-
它能比较容易地设计一个命令队列;
-
在需要的情况下,可以较容易地将命令记入日志;
-
允许接收请求地一方决定是否要否决请求;
-
可以容易地实现对请求地撤销和重做;
-
由于加进新地具体命令类不影响其他的类,因此增加新的具体命令类很容易;
-
把请求一个操作的对象与知道怎么执行一个操作的对象分隔开;
下面给出基本的类结构图。
上面这张图是命令模式的类结构的基本图。其实从这张图中还可以扩展出很多,细节就不说了,给大家留一些想象的空间,呵呵!
还是老规矩,给出简单的代码实现。
-
Receiver类接口
1
2
3
4
5
|
#import <Foundation/Foundation.h>
@interface
Receiver:
NSObject
-(
void
)Action;
@end
|
-
Receiver类实现
1
2
3
4
5
6
7
|
#import "Receiver.h"
@implementation
Receiver
-(
void
)Action{
NSLog
(@
"执行请求!"
);
}
@end
|
-
Commands类接口
1
2
3
4
5
6
7
8
9
|
#import <Foundation/Foundation.h>
@class
Receiver;
@interface
Commands :
NSObject
{
Receiver *myReceiver;
}
-(Commands*)MyInit:(Receiver*)receiver;
-(
void
)Execute;
@end
|
-
Commands类实现
1
2
3
4
5
6
7
8
9
10
11
12
|
#import "Commands.h"
#import "Receiver.h"
@implementation
Commands
-(Commands*)MyInit:(Receiver *)receiver{
myReceiver = receiver;
return
self
;
}
-(
void
)Execute{
return
;
}
@end
|
-
ConcreteCommands类接口
1
2
3
4
5
6
|
#import "Commands.h"
@class
Receiver;
@interface
ConcreteCommands :Commands
-(ConcreteCommands*)MyInit:(Receiver*)receiver;
@end
|
-
ConcreteCommands类实现
1
2
3
4
5
6
7
8
9
10
11
12
|
#import "ConcreteCommands.h"
#import "Receiver.h"
@implementation
ConcreteCommands
-(ConcreteCommands*)MyInit:(Receiver *)receiver{
myReceiver = receiver;
return
self
;
}
-(
void
)Execute{
[myReceiver Action];
}
@end
|
-
Invoker类接口
1
2
3
4
5
6
7
8
9
|
#import <Foundation/Foundation.h>
@class
Commands;
@interface
Invoker :
NSObject
{
Commands *myCommands;
}
-(
void
)SetCommands:(Commands*)commands;
-(
void
)ExecuteCommand;
@end
|
-
Invoker类实现
1
2
3
4
5
6
7
8
9
10
11
|
#import "Invoker.h"
#import "Commands.h"
@implementation
Invoker
-(
void
)SetCommands:(Commands *)commands{
myCommands = commands;
}
-(
void
)ExecuteCommand{
[myCommands Execute];
}
@end
|
-
Main方法调用
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
#import <Foundation/Foundation.h>
#import "Receiver.h"
#import "Commands.h"
#import "ConcreteCommands.h"
#import "Invoker.h"
int
main(
int
argc,
const
char
* argv[])
{
@autoreleasepool
{
Receiver *r = [[Receiver alloc]init];
Commands *c = [[ConcreteCommands alloc]MyInit:r];
Invoker *i = [[Invoker alloc]init];
[i SetCommands:c];
[i ExecuteCommand];
}
return
0;
}
|
展示完毕!
其实,单从类关系图中可以简单的看出,命令模式其实是把需求(Invoker)和具体实现(Receiver)通过命令层(Command)进行了解耦。具体实现过程根据不同的命令进行了区分。