前一篇《设计模式之感悟和实践(一)》介绍了如何去掉if...else
和switch...case
的应用场景,这篇文章我们将介绍另外一种场景的综合运用
如果没有看前一篇文章的,建议首先看一下。
前一篇文章我们是使用责任链设计模式教大家消除判断语句,具体如下格式:
//点击事件 - (IBAction)actionButton1:(id)sender { //这是伪代码,一个点击事件对应两种情况的处理 if(EVENT1){ //code处理 }else if(EVENT2){ //code处理 } }
经过设计模式的处理如下:
- (IBAction)actionButton1:(id)sender { MyHandle *myHandle = [[MyHandle alloc] initWithType:EVENT1]; [myHandle handleClick]; }
好处可谓是不言而喻。
有时候我们还会遇到如下的场景:
//点击事件1 - (IBAction)actionButton1:(id)sender { //这是伪代码,一个点击事件对应两种情况的处理 if(EVENT1){ //code处理 }else if(EVENT2){ //code处理 } } //点击事件2 - (IBAction)actionButton2:(id)sender { //这是伪代码,一个点击事件对应两种情况的处理 if(EVENT1){ //code处理 }else if(EVENT2){ //code处理 } }
以上场景则是两处点击事件:针对于EVENT1和EVENT2都有不同的代码处理,这时候我们怎么处理呢? 可能有的同学第一个映入眼帘的想法则是赋值一遍-
的处理即可 则变成如下:(IBAction)actionButton1:(id)sender
- (IBAction)actionButton2:(id)sender { MyHandle2 *myHandle = [[MyHandle2 alloc] initWithType:EVENT1]; [myHandle handleClick]; }
把所有的类再重新声明一遍就可解决。 这种方法针对这种情况确实也能处理,而且看着不错的样子哟。 不过缺点也显而易见:
类的数量暴增
针对EVENT1和EVENT2事件的处理分散到多个类中
不管有几个点击事件,我们都是同一个MyHandle
类来处理,这样可以大大简化使用。
类的设计还是之前那几个类:
让我们看看各个类中的设计:
ActionClickProtocol.h
@protocol ActionClickProtocol - (void)handleClick; - (void)handleClick2;//新增加的方法 - (void)setNext:(id)actionClickHandle; @end typedef NS_ENUM(NSUInteger, HandleType) { EVENT1, EVENT2, };
增加了- (void)handleClick2;
方法,所以ActionClickEvent1
、ActionClickEvent2
和ActionClickHandle
均会增加该方法。
ActionClickEvent1.m
@implementation ActionClickEvent1 -(void)handleClick{ NSLog(@"点击1事件1的处理"); } -(void)handleClick2{//新增加的方法 NSLog(@"点击2事件1的处理"); } @end
MyHandle.m
@implementation MyHandle - (instancetype)initWithType:(HandleType)type{ self = [super init]; if (self) { _type = type; _event1 = [[ActionClickEvent1 alloc] init]; _event1.type = EVENT1; _event2 = [[ActionClickEvent2 alloc] init]; _event2.type = EVENT2; [_event1 setNextHandle:_event2]; self.nextHandle = _event1; } return self; } - (void)handleClick{ if (self.nextHandle.type==self.type) { [self.nextHandle handleClick]; }else{ while (self.nextHandle.type!=self.type) { self.nextHandle = self.nextHandle.nextHandle; } [self.nextHandle handleClick]; } } - (void)handleClick2{//新增加的方法 if (self.nextHandle.type==self.type) { [self.nextHandle handleClick2]; }else{ while (self.nextHandle.type!=self.type) { self.nextHandle = self.nextHandle.nextHandle; } [self.nextHandle handleClick2]; } } @end
看完代码大家有没有恍然大悟呢。其实遇到场景多了,思路多了,思路自然而然就来了。 源码传送门
对于一个工程,如果基础打的好,对于后期维护就是如鱼得水,如果一开始工程就很烂,后期的维护真的是灾难啊!所以各位有没有遇到坑呢?反正我是遇到了深有体会。
本文由 投稿者 创作,文章地址:https://blog.isoyu.com/archives/shejimoshizhiganwuheshijianer.html
采用知识共享署名4.0 国际许可协议进行许可。除注明转载/出处外,均为本站原创或翻译,转载前请务必署名。最后编辑时间为:1月 10, 2019 at 09:27 下午