Command(命令模式)
将一个请求封装为一个对象,从而使你可用不同的请求对客户进行参数化;对请求排队或记录请求日志,以及支持可撤销的操作。
VC.m
//waiter用于接收各种类型的order。waiter是请求接收者。
//接收不同customer产生的不同order,并且都存入waiter这个接受者中,type表示不同类型的order。
HCDWaiter *waiter = [[HCDWaiter alloc]init];
//顾客一
HCDCustomr *customer = [[HCDCustomr alloc]init];
HCDOrder *customerOrder1 = [customer pushOrderWithString:@"顾客一要十串羊肉" type:orderTypeMutton];
HCDOrder *customerOrder2 = [customer pushOrderWithString:@"顾客一要十串鸭肉" type:orderTypeDuck];
[waiter addOrder:customerOrder1];
[waiter addOrder:customerOrder2];
//顾客二
HCDCustomr *customer1 = [[HCDCustomr alloc]init];
HCDOrder *customer1Order1 = [customer1 pushOrderWithString:@"顾客二要二十串鸡肉" type:orderTypeChicken];
HCDOrder *customer1Order2 = [customer1 pushOrderWithString:@"顾客二要二十串鸭肉" type:orderTypeDuck];
[waiter addOrder:customer1Order1];
[waiter addOrder:customer1Order2];
//顾客取消Order
[waiter deleteOrder:customer1Order2];
//waiter发送order,背后有一个HCDWorker这个单列作为行为实现者来处理具体的order。命令接收完毕,开始发送命令。
[waiter notifyOrder];
HCDWaiter.h
@interface HCDWaiter : NSObject
-(void)addOrder:(HCDOrder *)order;
-(void)deleteOrder:(HCDOrder *)order;
-(void)notifyOrder;
@end
HCDWaiter.m
@interface HCDWaiter ()
//用于存储命令列表
@property(nonatomic,strong)NSMutableArray *orderList;
@end
@implementation HCDWaiter
-(instancetype)init{
self = [super init];
if (self) {
_orderList = [NSMutableArray array];
}
return self;
}
-(void)addOrder:(HCDOrder *)order{
NSLog(@"添加Order");
[self.orderList addObject:order];
}
-(void)deleteOrder:(HCDOrder *)order{
NSLog(@"取消Order");
[self.orderList removeObject:order];
}
/*
命令接收完毕,开始执行命令
*/
-(void)notifyOrder{
NSLog(@"====开始执行Order===");
for (HCDOrder *order in self.orderList) {
[order executeOrder];
}
}
@end
网友评论