生活場景分析
今天來學習命令模式,先從一個生活中的例子入手吧虫溜,這樣理解起來也比較容易。大家應該有用過那種萬能遙控器吧股缸,就是那種能遙控各種品牌的空調(diào)或者電視的遙控器衡楞,我們只要在遙控器上設定具體的電器品牌,就可以遙控了敦姻,可以切換到任何支持的品牌的電器瘾境。
我們今天也來做一個萬能遙控器,如下圖所示:
請忽略這清奇的畫風镰惦,我們來看看具體的要求:
每排兩個按鈕迷守,分別實現(xiàn)打開和關(guān)閉電器的作用,除了如圖所示前三排按鈕對應的電器分別是:電燈旺入、cd兑凿、冰箱。我們可以完成這些電器的打開和關(guān)閉功能茵瘾。我們可以隨意設置每排的電器然后實現(xiàn)該電器的打開關(guān)閉功能礼华,也就是說遙控器不關(guān)心每排對應的電器具體是什么,用戶可以隨意設定排按鈕對應的電器拗秘,遙控器都可以對該電器實現(xiàn)打開和關(guān)閉的功能圣絮。
我們來分析下:
我們的要求是用戶可以隨意設置每排按鈕對應的具體電器,然后按下打開或者關(guān)閉按鈕雕旨,就可以執(zhí)行該電器的打開和關(guān)閉功能扮匠,換成任何其他電器都可以執(zhí)行打開和關(guān)閉功能捧请。我們用編程的思維抽象思考下,打開和關(guān)閉電器是一個請求命令棒搜,而具體的電器是命令的執(zhí)行者也就是接受者疹蛉,要想實現(xiàn)一個請求命令可以被任意命令接受者執(zhí)行,那么就必須對二者進行解耦帮非,讓請求命令不必關(guān)心具體的命令接受者和命令執(zhí)行的具體細節(jié)氧吐,只管發(fā)出命令,然后就可以被具體的命令接受者接受并執(zhí)行末盔。
那么如何實現(xiàn)二者的解耦呢筑舅?要讓兩者互相不知道,那么就必須引入一種中間量陨舱,這就是命令對象翠拣,它會把每個按鈕都和一個具體的命令對象關(guān)聯(lián)起來,命令對象會暴露一個接口給按鈕使用游盲,同時每個命令對象都會和具體的命令接受者關(guān)聯(lián)误墓,調(diào)用命令接受者的功能。此時按下按鈕益缎,就會調(diào)用關(guān)聯(lián)的命令對象的公開接口谜慌,然后命令對象內(nèi)部在調(diào)用具體的命令接受者(電器)的公開方法,執(zhí)行功能莺奔。
回到上面的例子就是欣范,用戶設置了每排按鈕對應的電器如上圖所示,此時用戶按下第一排的打開按鈕令哟,發(fā)出打開命令恼琼,觸發(fā)該按鈕關(guān)聯(lián)的命令對象,命令對象調(diào)用具體的命令接受者電燈屏富,調(diào)用電燈的打開功能晴竞。這樣遙控器只管發(fā)出命令,至于命令被誰執(zhí)行狠半,怎么執(zhí)行就不關(guān)他的事噩死。
具體代碼實現(xiàn)
1、定義命令對象的公共接口(按鈕執(zhí)行的動作)
這里定義按鈕的共同方法典予,實現(xiàn)打開功能
#import <Foundation/Foundation.h>
@protocol CommandInterface <NSObject>
-(void)execute;
@end
2甜滨、定義具體命令對象(每個按鈕關(guān)聯(lián)的操作)
下面我們來實現(xiàn)每個按鈕對應的具體命令對象,這些對象需要實現(xiàn)上面的協(xié)議方法瘤袖,然后調(diào)用具體的命令接受者的公開方法完成功能衣摩。
比如第一排的打開按鈕,關(guān)聯(lián)的操作是打開電燈。其他的按鈕類似
#import <Foundation/Foundation.h>
#import "CommandInterface.h"
#import "Light.h"
@interface LightOnCommand : NSObject<CommandInterface>
@property(strong,nonatomic)Light *light;
-(instancetype)initWithLight:(Light *)light;
@end
===============
#import "LightOnCommand.h"
@implementation LightOnCommand
-(instancetype)initWithLight:(Light *)light{
if (self == [super init]) {
self.light = light;
}
return self;
}
-(void)execute{
[self.light lightOn];
}
@end
#import <Foundation/Foundation.h>
#import "CommandInterface.h"
#import "Light.h"
@interface LightOffCommand : NSObject<CommandInterface>
@property(strong,nonatomic)Light *light;
-(instancetype)initWithLight:(Light *)light;
@end
===========
#import "LightOffCommand.h"
@implementation LightOffCommand
-(instancetype)initWithLight:(Light *)light{
if (self == [super init]) {
self.light = light;
}
return self;
}
-(void)execute{
[self.light lightOff];
}
@end
#import <Foundation/Foundation.h>
#import "CommandInterface.h"
#import "CDPlayer.h"
@interface CDPlayOnCommand : NSObject<CommandInterface>
@property(strong,nonatomic)CDPlayer *player;
-(instancetype)initWithPlayer:(CDPlayer *)player;
@end
===============
#import "CDPlayOnCommand.h"
@implementation CDPlayOnCommand
-(instancetype)initWithPlayer:(CDPlayer *)player{
if (self == [super init]) {
self.player = player;
}
return self;
}
-(void)execute{
[self.player CDOn];
[self.player setVolume:11];
}
@end
#import <Foundation/Foundation.h>
#import "CDPlayer.h"
#import "CommandInterface.h"
@interface CDPlayerOffCommand : NSObject<CommandInterface>
@property(strong,nonatomic)CDPlayer *player;
-(instancetype)initWithPlayer:(CDPlayer *)player;
@end
==========
#import "CDPlayerOffCommand.h"
@implementation CDPlayerOffCommand
-(instancetype)initWithPlayer:(CDPlayer *)player{
if (self == [super init]) {
self.player = player;
}
return self;
}
-(void)execute{
[self.player CDOff];
[self.player setVolume:0];
}
@end
3艾扮、定義命令接受者
每個命令接受者(各種電器)是具體功能的實現(xiàn)者既琴,命令對象會調(diào)用此處定義的公開方法去實現(xiàn)協(xié)議的方法-excute
比如電燈的打開和關(guān)閉功能,在這里具體去實現(xiàn)
#import <Foundation/Foundation.h>
@interface Light : NSObject
-(void)lightOn;
-(void)lightOff;
@end
===========
#import "Light.h"
@implementation Light
-(void)lightOn{
NSLog(@"燈被打開");
}
-(void)lightOff{
NSLog(@"燈被關(guān)閉");
}
@end
#import <Foundation/Foundation.h>
@interface CDPlayer : NSObject
-(void)CDOn;
-(void)CDOff;
-(void)setVolume:(NSInteger)volume;
@end
=========
#import "CDPlayer.h"
@implementation CDPlayer
-(void)CDOn{
NSLog(@"CD播放器被打開");
}
-(void)CDOff{
NSLog(@"CD播放器被關(guān)閉");
}
-(void)setVolume:(NSInteger)volume{
NSLog(@"設置聲音大小為:%zd",volume);
}
@end
4泡嘴、設置命令調(diào)用者(遙控器)
我們現(xiàn)在需要定義遙控器每排按鈕的命令甫恩,我們把打開和關(guān)閉的命令對象分別存入到兩個不同的數(shù)組,然后根據(jù)按鈕的排數(shù)去數(shù)組中取出響應的命令執(zhí)行酌予。
同時此處定義了一個公開的方法setCommandWithSlot
供命令裝配者來給自己的每個按鈕綁定具體的命令對象磺箕。
#import <Foundation/Foundation.h>
#import "CommandInterface.h"
@interface RemoteControl : NSObject
@property(strong,nonatomic)id<CommandInterface> slot;
-(void)onButtonClickWithSlot:(NSInteger)slot;
-(void)offButtonClickWithSlot:(NSInteger)slot;
-(void)setCommandWithSlot:(NSInteger )slot onCommand:(id<CommandInterface>)onCommand offCommand:(id<CommandInterface>)offCommand;
@end
====================
#import "RemoteControl.h"
#import "noCommand.h"
@interface RemoteControl()
@property(nonatomic,strong)NSMutableArray<id<CommandInterface>> *onCommandArr;
@property(nonatomic,strong)NSMutableArray<id<CommandInterface>> *offCommandArr;
@end
@implementation RemoteControl
-(void)onButtonClickWithSlot:(NSInteger)slot{
[self.onCommandArr[slot] execute];
}
-(void)offButtonClickWithSlot:(NSInteger)slot{
[self.offCommandArr[slot] execute];
}
- (instancetype)init
{
self = [super init];
if (self) {
self.onCommandArr = [NSMutableArray array];
self.offCommandArr = [NSMutableArray array];
self.completeCommandsArr = [NSMutableArray array];
id<CommandInterface>noCommands = [[noCommand alloc]init];
for (int i = 0; i< 4; i++) {
self.offCommandArr[i] = noCommands;
self.onCommandArr[i] = noCommands;
}
self.undoCommand = [[noCommand alloc]init];
}
return self;
}
-(void)setCommandWithSlot:(NSInteger )slot onCommand:(id<CommandInterface>)onCommand offCommand:(id<CommandInterface>)offCommand
{
self.onCommandArr[slot] = onCommand;
self.offCommandArr[slot] = offCommand;
}
@end
注意到我們在init方法初始化的時候,給兩個命令對象數(shù)組都預先存入了nocommand對象抛虫,這是因為每排按鈕最好默認綁定一個命令對象松靡,實現(xiàn)空操作,這樣如果需要重新綁定某個按鈕的命令對象建椰,就可以覆蓋nocommand對象即可雕欺,如果沒有覆蓋就是默認的空操作,這樣客戶端如果調(diào)用到綁定nocommand命令對象的按鈕也不會報錯棉姐。
nocommand實現(xiàn)如下:
#import <Foundation/Foundation.h>
#import "CommandInterface.h"
@interface noCommand : NSObject<CommandInterface>
@end
============
#import "noCommand.h"
@implementation noCommand
-(void)execute{
NSLog(@"該插槽沒有安裝命令");
}
@end
5屠列、定義命令裝配者
我們通過上面幾個步驟定義了命令對象和命令調(diào)用者(遙控器),現(xiàn)在我們需要把這些命令對象對應安裝到遙控器的不同按鈕上伞矩。
#import <Foundation/Foundation.h>
#import "RemoteControl.h"
@interface RemoteLoader : NSObject
- (instancetype)initWithRm:(RemoteControl*)RM;
@end
============
#import "RemoteLoader.h"
#import "Light.h"
#import "LightOnCommand.h"
#import "LightOffCommand.h"
#import "CDPlayer.h"
#import "CDPlayOnCommand.h"
#import "CDPlayerOffCommand.h"
#import "macroCommand.h"
@interface RemoteLoader ()
@property(strong,nonatomic)RemoteControl *RM;
@end
@implementation RemoteLoader
- (instancetype)initWithRm:(RemoteControl*)remote
{
self = [super init];
if (self) {
self.RM = remote;
[self configSlotCommand];
}
return self;
}
-(void)configSlotCommand{
Light *light = [Light new];
LightOnCommand *lightOn = [[LightOnCommand alloc]initWithLight:light];
LightOffCommand *LightOff = [[LightOffCommand alloc]initWithLight:light];
[self.RM setCommandWithSlot:0 onCommand:lightOn offCommand:LightOff];
CDPlayer *player = [CDPlayer new];
CDPlayOnCommand *playerOn = [[CDPlayOnCommand alloc]initWithPlayer:player];
CDPlayerOffCommand *playerOff = [[CDPlayerOffCommand alloc]initWithPlayer:player];
[self.RM setCommandWithSlot:1 onCommand:playerOn offCommand:playerOff];
}
@end
6笛洛、客戶端調(diào)用
現(xiàn)在我們已經(jīng)完成了遙控器的實現(xiàn),這里我們只實現(xiàn)第一排和第二排按鈕乃坤,分別是電燈和CD的打開關(guān)閉操作撞蜂。下面我們來看看調(diào)用
RemoteControl *remote = [[RemoteControl alloc]init];
RemoteLoader *loader = [[RemoteLoader alloc]initWithRm:remote];
[remote onButtonClickWithSlot:0];
NSLog(@"-----------------------");
[remote offButtonClickWithSlot:0];
NSLog(@"-----------------------");
[remote onButtonClickWithSlot:1];
NSLog(@"-----------------------");
[remote offButtonClickWithSlot:1];
NSLog(@"-----------------------");
[remote onButtonClickWithSlot:3];
NSLog(@"-----------------------");
輸出如下:
2016-12-03 13:00:18.208 命令模式[37394:323525] 燈被打開
2016-12-03 13:00:18.208 命令模式[37394:323525] -----------------------
2016-12-03 13:00:18.208 命令模式[37394:323525] 燈被關(guān)閉
2016-12-03 13:00:18.208 命令模式[37394:323525] -----------------------
2016-12-03 13:00:18.208 命令模式[37394:323525] CD播放器被打開
2016-12-03 13:00:18.208 命令模式[37394:323525] 設置聲音大小為:11
2016-12-03 13:00:18.208 命令模式[37394:323525] -----------------------
2016-12-03 13:00:18.208 命令模式[37394:323525] CD播放器被關(guān)閉
2016-12-03 13:00:18.208 命令模式[37394:323525] 設置聲音大小為:0
2016-12-03 13:00:18.209 命令模式[37394:323525] -----------------------
2016-12-03 13:00:18.209 命令模式[37394:323525] 該插槽沒有安裝命令
-----------------------
此時如果想要更換每排按鈕對應的電器只需要修改RemoteLoader即可,假設現(xiàn)在把第一排按鈕對應的電器換成CD播放器侥袜,第二排的電器換成電燈,只需要做如下設置即可
-(void)configSlotCommand{
Light *light = [Light new];
LightOnCommand *lightOn = [[LightOnCommand alloc]initWithLight:light];
LightOffCommand *LightOff = [[LightOffCommand alloc]initWithLight:light];
[self.RM setCommandWithSlot:1 onCommand:lightOn offCommand:LightOff];
CDPlayer *player = [CDPlayer new];
CDPlayOnCommand *playerOn = [[CDPlayOnCommand alloc]initWithPlayer:player];
CDPlayerOffCommand *playerOff = [[CDPlayerOffCommand alloc]initWithPlayer:player];
[self.RM setCommandWithSlot:0 onCommand:playerOn offCommand:playerOff];
}
改為:
-(void)configSlotCommand{
Light *light = [Light new];
LightOnCommand *lightOn = [[LightOnCommand alloc]initWithLight:light];
LightOffCommand *LightOff = [[LightOffCommand alloc]initWithLight:light];
[self.RM setCommandWithSlot:0 onCommand:lightOn offCommand:LightOff];
CDPlayer *player = [CDPlayer new];
CDPlayOnCommand *playerOn = [[CDPlayOnCommand alloc]initWithPlayer:player];
CDPlayerOffCommand *playerOff = [[CDPlayerOffCommand alloc]initWithPlayer:player];
[self.RM setCommandWithSlot:1 onCommand:playerOn offCommand:playerOff];
}
想把現(xiàn)有的每排按鈕對應的電器換成其他電器也非常容易溉贿,重新創(chuàng)建一個命令對象枫吧,然后設置到對應的排數(shù)即可。
執(zhí)行過程分析
下面我們使用UML圖的方式來分析下宇色,上面的過程是如何完成的九杂。
小結(jié)
通過上面的例子我們可以看到命令調(diào)用者和命令接受者之間完全解耦了,二者都不需要知道對方宣蠕,只需要通過命令對象這個中間量來聯(lián)系即可例隆,這樣不管命令接受者如何變化,只需要改變命令調(diào)用者的每個命令關(guān)聯(lián)的命令對象即可抢蚀,而無需更改命令調(diào)用者的任何代碼镀层,而客戶端是面向的命令調(diào)用者編程,那么客戶端代碼也不需要修改皿曲,只需要擴展即可唱逢。
撤銷操作和宏命令
想象下我們下班回家吴侦,一進家門,打開電燈坞古,然后打開CD播放器备韧,開始播放音樂,多么美妙痪枫。但是使用上面的代碼我們需要一個個的電器去打開织堂,太麻煩,能不能實現(xiàn)按一個按鈕就打開電燈和CD播放器呢奶陈?這就需要用到宏命令易阳,所謂宏命令就是把許多命令對象集中起來一起執(zhí)行。
另外我們我們還可以實現(xiàn)命令撤銷功能尿瞭,這里的命令撤銷功能比較簡單闽烙,只需要執(zhí)行相反操作就可以了,比如執(zhí)行的動作是開燈声搁,那么撤銷操作就是關(guān)燈黑竞。
實際使用過程中的撤銷功能可能比較復雜,因為需要記錄下命令執(zhí)行前的狀態(tài)疏旨,然后撤銷功能必須回到當初的狀態(tài)很魂,這個當我們講到備忘錄模式的時候再回頭講如何實現(xiàn)
1、實現(xiàn)宏命令
#import <Foundation/Foundation.h>
#import "CommandInterface.h"
@interface macroCommand : NSObject<CommandInterface>
@property(strong,nonatomic)NSArray<id<CommandInterface>> *commandsArr;
- (instancetype)initWithCommands:(NSArray<id<CommandInterface>>*)commands;
@end
============
#import "macroCommand.h"
@implementation macroCommand
- (instancetype)initWithCommands:(NSArray<id<CommandInterface>>*)commands
{
self = [super init];
if (self) {
self.commandsArr = commands;
}
return self;
}
-(void)execute{
for (id<CommandInterface>command in self.commandsArr) {
[command execute];
}
}
//和單個命令的撤銷操作類似檐涝,就不在演示了
-(void)undo{
NSLog(@"宏命令懶得寫撤銷操作");
}
@end
把宏命令對象對應到第三排按鈕遏匆,修改remoteLoader類
-(void)configSlotCommand{
Light *light = [Light new];
LightOnCommand *lightOn = [[LightOnCommand alloc]initWithLight:light];
LightOffCommand *LightOff = [[LightOffCommand alloc]initWithLight:light];
[self.RM setCommandWithSlot:1 onCommand:lightOn offCommand:LightOff];
CDPlayer *player = [CDPlayer new];
CDPlayOnCommand *playerOn = [[CDPlayOnCommand alloc]initWithPlayer:player];
CDPlayerOffCommand *playerOff = [[CDPlayerOffCommand alloc]initWithPlayer:player];
[self.RM setCommandWithSlot:0 onCommand:playerOn offCommand:playerOff];
NSArray *onCommandArr = [NSArray arrayWithObjects:lightOn,playerOn, nil];
NSArray *offCommandArr = [NSArray arrayWithObjects:LightOff,playerOff, nil];
macroCommand *onMacro = [[macroCommand alloc]initWithCommands:onCommandArr];
macroCommand *offMacro = [[macroCommand alloc]initWithCommands:offCommandArr];
[self.RM setCommandWithSlot:2 onCommand:onMacro offCommand:offMacro];
}
2、實現(xiàn)命令撤銷功能
給命令對象接口添加undo功能
#import <Foundation/Foundation.h>
@protocol CommandInterface <NSObject>
-(void)execute;
-(void)undo;
@end
給每個電器添加撤銷功能
下面是給lightOnCommand命令對象添加undo功能谁榜,執(zhí)行和excute相反的操作即可幅聘。其他命令對象類似。
#import "LightOnCommand.h"
@implementation LightOnCommand
-(instancetype)initWithLight:(Light *)light{
if (self == [super init]) {
self.light = light;
}
return self;
}
-(void)execute{
[self.light lightOn];
}
-(void)undo{
[self.light lightOff];
}
@end
給remoteControl添加撤銷功能
#import "RemoteControl.h"
#import "noCommand.h"
@interface RemoteControl()
@property(nonatomic,strong)NSMutableArray<id<CommandInterface>> *onCommandArr;
@property(nonatomic,strong)NSMutableArray<id<CommandInterface>> *offCommandArr;
@property(nonatomic,strong)id<CommandInterface> undoCommand;
@property(nonatomic,strong)NSMutableArray <id<CommandInterface>> *completeCommandsArr;
@end
@implementation RemoteControl
-(void)onButtonClickWithSlot:(NSInteger)slot{
[self.onCommandArr[slot] execute];
self.undoCommand = self.onCommandArr[slot];
[self.completeCommandsArr addObject:self.onCommandArr[slot]];
}
-(void)offButtonClickWithSlot:(NSInteger)slot{
[self.offCommandArr[slot] execute];
self.undoCommand = self.offCommandArr[slot];
[self.completeCommandsArr addObject:self.offCommandArr[slot]];
}
//撤銷最后一步操作
-(void)undoButtonClick{
[self.undoCommand undo];
}
//撤銷全部操作
-(void)undoAllOperation{
for (id<CommandInterface>command in self.completeCommandsArr) {
[command undo];
}
}
- (instancetype)init
{
self = [super init];
if (self) {
self.onCommandArr = [NSMutableArray array];
self.offCommandArr = [NSMutableArray array];
self.completeCommandsArr = [NSMutableArray array];
id<CommandInterface>noCommands = [[noCommand alloc]init];
for (int i = 0; i< 4; i++) {
self.offCommandArr[i] = noCommands;
self.onCommandArr[i] = noCommands;
}
self.undoCommand = [[noCommand alloc]init];
}
return self;
}
-(void)setCommandWithSlot:(NSInteger )slot onCommand:(id<CommandInterface>)onCommand offCommand:(id<CommandInterface>)offCommand
{
self.onCommandArr[slot] = onCommand;
self.offCommandArr[slot] = offCommand;
}
@end
上面是一個生活中的例子窃植,我們上面用到的解決問題的思路在設計模式中我們叫做:命令模式帝蒿。
下面我們來具體看看命令模式的真面目
定義
將一個請求封裝為一個對象,從而使你可用不同的請求對客戶進行參數(shù)化;對請求排隊或記錄請求日志,以及支持可撤消的操作。
通過上面的案例我們可以總結(jié)出巷怜,命令模式的本質(zhì)就是把請求封裝成對象葛超,既然是對象,那么就可以對這個對象進行傳遞延塑、調(diào)用绣张、宏命令、隊列化关带、持久化等一系列操作侥涵。
命令模式讓命令的發(fā)起者和命令的接受者完全解耦,在他們之間通過命令對象來實現(xiàn)連通。這樣就有如下好處:
- 把請求封裝起來独令,可以動態(tài)的進行隊列化端朵、持久化等操作,滿足各種業(yè)務需求
- 可以把多個簡單的命令組合成一個宏命令燃箭,從而簡化操作冲呢,完成復雜的功能
- 擴展性良好。由于命令的發(fā)起者和接受者完全解耦招狸,那么這個時候添加和修改任何命令敬拓,只需要設置好對應的命令和命令對象即可,無需對原有系統(tǒng)進行修改
在實際場景中裙戏,如果出現(xiàn)有如下需求乘凸,那么就可以考慮使用命令模式了
UML結(jié)構(gòu)圖及說明
把這幅圖和上面的執(zhí)行過程圖好好對比下,可以加深理解
提醒下:實際開發(fā)過程中累榜,client和invoker可以融合在一起實現(xiàn)营勤。
動機
有時必須向某對象提交請求,但并不知道關(guān)于請求的接受者的任何信息。比如上面的遙控器需要執(zhí)行打開或者關(guān)閉電器的操作壹罚,但是它并不知道這個命令被那個具體的電器執(zhí)行葛作。
這個時候我們就可以使用命令模式來完成這一需求。通過將請求本身變成一個對象來使工具箱對象可向未指定的應用對象提出請求猖凛。 這個對象可被存儲并像其他的對象一樣被傳遞赂蠢。這一模式的關(guān)鍵是一個抽象的 command類, 它定義了一個執(zhí)行操作的接口。其最簡單的形式是一個抽象的 excute操作辨泳。具體的 command 子類將接收者作為其一個實例變量,并實現(xiàn) excute 操 作 , 指 定 接 收 者 采 取 的 動 作 虱岂。 而 接 收 者 有執(zhí)行該請求所需的具體信息。
通過上面的講解相信大家對命令模式已經(jīng)有了一個感性認識菠红,下面我們來看看命令模式在實際應用中的兩個例子加深理解第岖。
命令日志化
1、需求分析
大家應該遇到過window莫名其妙的開機無法進入系統(tǒng)的情況试溯,此時進入安全模式绍傲,可以選擇最后一次正確的操作,然后系統(tǒng)開始回滾操作耍共,最后就可以正常進入系統(tǒng)了。
命令日志化就可以實現(xiàn)類似的功能猎塞,我們可以把執(zhí)行過得命令存儲起來试读,當系統(tǒng)出現(xiàn)問題或者執(zhí)行過程中斷,我們可以把命令取出來進行再次執(zhí)行荠耽,也就是回滾操作钩骇。
實現(xiàn)起來也比較簡單,就是對執(zhí)行過的命令對象進行序列化,然后存儲起來倘屹,在需要使用的時候再次執(zhí)行即可银亲。
在iOS中我們可以通過NSCoding的兩個協(xié)議方法實現(xiàn)對象序列化
- (void)encodeWithCoder:(NSCoder *)aCoder
- (id)initWithCoder:(NSCoder *)aDecoder
我們現(xiàn)在要實現(xiàn)如下要求,假設程序啟動的時候執(zhí)行如下命令:
RemoteControl *remote = [[RemoteControl alloc]init];
RemoteLoader *loader = [[RemoteLoader alloc]initWithRm:remote];
//測試每個按鈕的命令
[remote onButtonClickWithSlot:0];
[remote offButtonClickWithSlot:0];
[remote onButtonClickWithSlot:1];
[remote offButtonClickWithSlot:1];
//測試宏命令
[remote onButtonClickWithSlot:2];
[remote offButtonClickWithSlot:2];
此時輸出如下:
2016-12-04 11:57:38.505 命令模式[39084:534547] 燈被打開
2016-12-04 11:57:38.505 命令模式[39084:534547] 燈被關(guān)閉
2016-12-04 11:57:38.505 命令模式[39084:534547] CD播放器被打開
2016-12-04 11:57:38.505 命令模式[39084:534547] 設置聲音大小為:11
2016-12-04 11:57:38.506 命令模式[39084:534547] CD播放器被關(guān)閉
2016-12-04 11:57:38.506 命令模式[39084:534547] 設置聲音大小為:0
2016-12-04 11:57:38.506 命令模式[39084:534547] 燈被打開
2016-12-04 11:57:38.507 命令模式[39084:534547] CD播放器被打開
2016-12-04 11:57:38.507 命令模式[39084:534547] 設置聲音大小為:11
2016-12-04 11:57:38.507 命令模式[39084:534547] 燈被關(guān)閉
2016-12-04 11:57:38.507 命令模式[39084:534547] CD播放器被關(guān)閉
2016-12-04 11:57:38.507 命令模式[39084:534547] 設置聲音大小為:0
當殺死程序纽匙,再次啟動的時候务蝠,我們不用執(zhí)行上面的代碼,只需要取出我們事先存儲的命令對象進行回滾烛缔,就可以再現(xiàn)上面的輸出馏段。
2、序列化命令對象和命令接受者
下面來看看如何實現(xiàn):
因為我們需要序列化每個命令對象和命令接受者践瓷,這里我們采用NSCoding的方式來實現(xiàn)院喜,為了方便,我把序列化操作抽成了一個宏晕翠,保存在serialObject.h
文件
如下所示:
#define SERIALIZE_CODER_DECODER() \
\
- (id)initWithCoder:(NSCoder *)coder \
{ \
NSLog(@"%s",__func__); \
Class cls = [self class]; \
while (cls != [NSObject class]) { \
/*判斷是自身類還是父類*/ \
BOOL bIsSelfClass = (cls == [self class]); \
unsigned int iVarCount = 0; \
unsigned int propVarCount = 0; \
unsigned int sharedVarCount = 0; \
Ivar *ivarList = bIsSelfClass ? class_copyIvarList([cls class], &iVarCount) : NULL;/*變量列表喷舀,含屬性以及私有變量*/ \
objc_property_t *propList = bIsSelfClass ? NULL : class_copyPropertyList(cls, &propVarCount);/*屬性列表*/ \
sharedVarCount = bIsSelfClass ? iVarCount : propVarCount; \
\
for (int i = 0; i < sharedVarCount; i++) { \
const char *varName = bIsSelfClass ? ivar_getName(*(ivarList + i)) : property_getName(*(propList + i)); \
NSString *key = [NSString stringWithUTF8String:varName]; \
id varValue = [coder decodeObjectForKey:key]; \
NSArray *filters = @[@"superclass", @"description", @"debugDescription", @"hash"]; \
if (varValue && [filters containsObject:key] == NO) { \
[self setValue:varValue forKey:key]; \
} \
} \
free(ivarList); \
free(propList); \
cls = class_getSuperclass(cls); \
} \
return self; \
} \
\
- (void)encodeWithCoder:(NSCoder *)coder \
{ \
NSLog(@"%s",__func__); \
Class cls = [self class]; \
while (cls != [NSObject class]) { \
/*判斷是自身類還是父類*/ \
BOOL bIsSelfClass = (cls == [self class]); \
unsigned int iVarCount = 0; \
unsigned int propVarCount = 0; \
unsigned int sharedVarCount = 0; \
Ivar *ivarList = bIsSelfClass ? class_copyIvarList([cls class], &iVarCount) : NULL;/*變量列表,含屬性以及私有變量*/ \
objc_property_t *propList = bIsSelfClass ? NULL : class_copyPropertyList(cls, &propVarCount);/*屬性列表*/ \
sharedVarCount = bIsSelfClass ? iVarCount : propVarCount; \
\
for (int i = 0; i < sharedVarCount; i++) { \
const char *varName = bIsSelfClass ? ivar_getName(*(ivarList + i)) : property_getName(*(propList + i)); \
NSString *key = [NSString stringWithUTF8String:varName]; \
/*valueForKey只能獲取本類所有變量以及所有層級父類的屬性淋肾,不包含任何父類的私有變量(會崩潰)*/ \
id varValue = [self valueForKey:key]; \
NSArray *filters = @[@"superclass", @"description", @"debugDescription", @"hash"]; \
if (varValue && [filters containsObject:key] == NO) { \
[coder encodeObject:varValue forKey:key]; \
} \
} \
free(ivarList); \
free(propList); \
cls = class_getSuperclass(cls); \
} \
}
在需要序列化的地方只需要導入該.h文件硫麻,然后寫一句SERIALIZE_CODER_DECODER()
即可
下面我們來看看如何序列化LightOnCommand
,如下操作即可
#import "LightOnCommand.h"
#import "serialObject.h"
#import <objc/runtime.h>
@implementation LightOnCommand
-(instancetype)initWithLight:(Light *)light{
if (self == [super init]) {
self.light = light;
}
return self;
}
-(void)execute{
[self.light lightOn];
}
-(void)undo{
[self.light lightOff];
}
SERIALIZE_CODER_DECODER()
@end
其他的command對象都進行如此操作進行序列化巫员,這里就不再演示庶香,注意命令接受這light和CDPlayer也需要序列化,做法和這里類似简识,就不再贅述赶掖。
3、保存序列化后的命令對象
#import "RemoteLoader.h"
#import "Light.h"
#import "LightOnCommand.h"
#import "LightOffCommand.h"
#import "CDPlayer.h"
#import "CDPlayOnCommand.h"
#import "CDPlayerOffCommand.h"
#import "macroCommand.h"
@interface RemoteLoader ()
@property(strong,nonatomic)RemoteControl *RM;
@property(strong,nonatomic)NSArray *completedCommandsArr;
@end
@implementation RemoteLoader
- (instancetype)initWithRm:(RemoteControl*)remote
{
self = [super init];
if (self) {
self.RM = remote;
[self configSlotCommand];
}
return self;
}
-(void)configSlotCommand{
Light *light = [Light new];
LightOnCommand *lightOn = [[LightOnCommand alloc]initWithLight:light];
LightOffCommand *LightOff = [[LightOffCommand alloc]initWithLight:light];
[self.RM setCommandWithSlot:0 onCommand:lightOn offCommand:LightOff];
CDPlayer *player = [CDPlayer new];
CDPlayOnCommand *playerOn = [[CDPlayOnCommand alloc]initWithPlayer:player];
CDPlayerOffCommand *playerOff = [[CDPlayerOffCommand alloc]initWithPlayer:player];
[self.RM setCommandWithSlot:1 onCommand:playerOn offCommand:playerOff];
NSArray *onCommandArr = [NSArray arrayWithObjects:lightOn,playerOn, nil];
NSArray *offCommandArr = [NSArray arrayWithObjects:LightOff,playerOff, nil];
macroCommand *onMacro = [[macroCommand alloc]initWithCommands:onCommandArr];
macroCommand *offMacro = [[macroCommand alloc]initWithCommands:offCommandArr];
[self.RM setCommandWithSlot:2 onCommand:onMacro offCommand:offMacro];
//序列化命令對象七扰,然后保存
self.completedCommandsArr = @[lightOn,LightOff,playerOn,playerOff,onMacro,offMacro];
NSData *data1 = [NSKeyedArchiver archivedDataWithRootObject:self.completedCommandsArr];
[[NSUserDefaults standardUserDefaults]setObject:data1 forKey:@"serialCommands"];
[[NSUserDefaults standardUserDefaults]synchronize];
}
@end
4奢赂、客戶端調(diào)用
客戶端調(diào)用方法如下:
NSData *data = [[NSUserDefaults standardUserDefaults]objectForKey:@"serialCommands"];
NSArray *commands = [NSKeyedUnarchiver unarchiveObjectWithData:data];//反序列化
for (id<CommandInterface> command in commands) {
[command execute];
}
#########斷點###########
//測試命令
RemoteControl *remote = [[RemoteControl alloc]init];
RemoteLoader *loader = [[RemoteLoader alloc]initWithRm:remote];
//測試每個按鈕的命令
[remote onButtonClickWithSlot:0];
[remote offButtonClickWithSlot:0];
[remote onButtonClickWithSlot:1];
[remote offButtonClickWithSlot:1];
//測試宏命令
[remote onButtonClickWithSlot:2];
[remote offButtonClickWithSlot:2];
當?shù)谝淮芜\行程序到斷點的時候,我們可以發(fā)現(xiàn)此時的commands數(shù)組是空的颈走,如圖所示
因為此時還沒有執(zhí)行命令膳灶,當然也就沒有命令對象可以存儲。我們跳過斷點繼續(xù)執(zhí)行立由,此時輸出如需求分析中所展示的一樣
現(xiàn)在再次啟動程序轧钓,執(zhí)行到斷點處,查看commands如下所示:
可以發(fā)現(xiàn)此時commands包含了上次執(zhí)行的命令對象和命令接受者锐膜,同時毕箍,執(zhí)行到斷點處的輸出也和需求分析中展示的一樣。說明我們成功的實現(xiàn)了命令回滾道盏。
命令隊列化
既然命令對象可以被持久化而柑,那么當然也可以隊列化文捶,說簡單點,就是把各種命令對象存放到隊列里面媒咳,然后分發(fā)給命令接受者處理的過程就是命令隊列化粹排。通常會用多線程來處理命令隊列。
命令對象在一頭被依次不斷放入一個隊列涩澡,然后在隊列的另一頭顽耳,多線程把這些命令對象取出來,調(diào)用它的execute()方法執(zhí)行操作筏养,操作完畢斧抱,丟棄,然后開始調(diào)用下一個命令對象渐溶,如此循環(huán)往復辉浦。
如果需要實現(xiàn)一個功能完全的隊列,會相當麻煩茎辐,因為要保證多線程之間的調(diào)度宪郊,簡單點的就是使用數(shù)組當隊列,然后存入和取出命令對象的時候加上同步鎖來保證不會造成資源競爭拖陆。
實現(xiàn)比較簡單弛槐,就不演示了,大家可以自己去實現(xiàn)下試試依啰。