设计模式之构造者模式
构造者模式:讲一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示。
如果我们使用了构建者模式,那么用户就只需要指定需要构建的类型就可以得到它们,而具体构建的过程和细节就不需要知道了。
有这样一个编程实践,如果我们需要画一个人,那么肯定是都需要话头、身体、左手、右手、左脚、右脚。
代码如下:
#import <UIKit/UIKit.h>
@interface ZYThinPersonView : UIView
@end
#import "ZYThinPersonView.h"
@interface ZYThinPersonView ()
@end
@implementation ZYThinPersonView
- (void)drawRect:(CGRect)rect
{
CGContextRef ref = UIGraphicsGetCurrentContext();
CGContextAddArc(ref, 100, 100, 30, 0, 2 * M_PI, 0);
CGContextAddRect(ref, CGRectMake(90, 130, 20, 80));
CGContextMoveToPoint(ref, 90, 130);
CGContextAddLineToPoint(ref, 60, 170);
CGContextMoveToPoint(ref, 110, 130);
CGContextAddLineToPoint(ref, 140, 170);
CGContextMoveToPoint(ref, 90, 210);
CGContextAddLineToPoint(ref, 50, 270);
CGContextMoveToPoint(ref, 110, 210);
CGContextAddLineToPoint(ref, 150, 270);
CGContextStrokePath(ref);
}
@end
viewController里面的代码:
#import "ViewController.h"
#import "ZYThinPersonView.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
ZYThinPersonView *personView = [[ZYThinPersonView alloc] initWithFrame:[UIScreen mainScreen].bounds];
personView.backgroundColor = [UIColor yellowColor];
[self.view addSubview:personView];
}
@end
效果运行图:

我使用的是CoreGraphics里面的画图技术,一切看起来好像都搞定了,但是这个时候,如果要需要增加一个胖纸咋办?
恩,有一种这样的解决方案,再添加一个胖纸类就可以了......说起来,也的确是这样的,但是,如果稍不注意,我们就又可以少画了一只脚啥的,这个时候可以考虑采用继承写,代码如下:
#import "ZYPersonView.h"
@interface ZYFatPersonView : ZYPersonView
@end
#import "ZYFatPersonView.h"
@implementation ZYFatPersonView
- (void)drawRect:(CGRect)rect
{
[super drawRect:rect];
CGContextRef ref = UIGraphicsGetCurrentContext();
CGContextAddArc(ref, 100, 100, 30, 0, 2 * M_PI, 0);
CGContextAddRect(ref, CGRectMake(80, 130, 40, 80));
CGContextMoveToPoint(ref, 80, 130);
CGContextAddLineToPoint(ref, 60, 170);
CGContextMoveToPoint(ref, 120, 130);
CGContextAddLineToPoint(ref, 140, 170);
CGContextMoveToPoint(ref, 80, 210);
CGContextAddLineToPoint(ref, 50, 270);
CGContextMoveToPoint(ref, 120, 210);
CGContextAddLineToPoint(ref, 150, 270);
CGContextStrokePath(ref);
}
@end
效果图:

代码也没必要展示了,我感觉由于语言特性的问题,画小人并不能很好的展示这个模式。在iOS中,如果想要画图,那么需要在drawRect方法里面画,需要开启
CGContextRef,太麻烦了.......这次的构造者模式就写到这吧,下次遇到好的再补充。
朋友们,虽然这个世界日益浮躁起来,只要能够为了当时纯粹的梦想和感动坚持努力下去,不管其它人怎么样,我们也能够保持自己的本色走下去。

浙公网安备 33010602011771号