简单⼯工⼚厂模式 (Simple Factory Pattern)
@interface ViewController () { Shape *_shape; } @end @implementation ViewController - (void)loadView { //设置画板 self.view=[[SimpleDrawBoard alloc]init]; self.view.backgroundColor=[UIColor whiteColor]; } - (void)viewDidLoad { [super viewDidLoad]; } - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { UITouch *touch=[touches anyObject]; CGPoint point=[touch locationInView:self.view]; //工厂生产形状 _shape=[Factory shapeWithType:kRud]; // _shape.fillColor=[UIColor blackColor]; [_shape addPoint:point]; } - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event { UITouch *touch=[touches anyObject]; CGPoint point=[touch locationInView:self.view]; SimpleDrawBoard *board=(SimpleDrawBoard *)self.view; [_shape addPoint:point]; [board drawShape:_shape]; } - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event { UITouch *touch=[touches anyObject]; CGPoint point=[touch locationInView:self.view]; [_shape addPoint:point]; SimpleDrawBoard *board=(SimpleDrawBoard *)self.view; [board drawShape:_shape]; } // // SimpleDrawBoard.m // Facetory-0904 // // Created by apple on 14-9-4. // Copyright (c) 2014年 apple. All rights reserved. // #import "SimpleDrawBoard.h" @interface SimpleDrawBoard() { Shape *_shape; } @end @implementation SimpleDrawBoard - (instancetype)initWithFrame:(CGRect)frame { self = [super initWithFrame:frame]; if (self) { // Initialization code } return self; } // Only override drawRect: if you perform custom drawing. // An empty implementation adversely affects performance during animation. - (void)drawRect:(CGRect)rect { CGContextRef context=UIGraphicsGetCurrentContext(); [_shape draw:context]; } - (void)drawShape:(Shape *)shape { _shape=shape; [self setNeedsDisplay]; } @end // // Shape.m // Facetory-0904 // // Created by apple on 14-9-4. // Copyright (c) 2014年 apple. All rights reserved. // #import "Shape.h" @implementation Shape - (void)addPoint:(CGPoint)point { [self doesNotRecognizeSelector:_cmd]; } - (void)draw:(CGContextRef)context { if (_fillColor) { [_fillColor setFill]; } if (_lineWidth) { CGContextSetLineWidth(context, _lineWidth); } if (_strokColor) { [_strokColor setStroke]; } } @end // // Rud.m // SimpleDrawBoard // // Created by apple on 14-9-4. // Copyright (c) 2014年 戴维营教育. All rights reserved. // #import "Rud.h" #include "math.h" @interface Rud () { CGPoint _startPoint; CGPoint _endPoint; CGFloat rid; BOOL bEnd; } @end @implementation Rud - (void)addPoint:(CGPoint)position { if (!bEnd) { _startPoint = position; bEnd = YES; } else { _endPoint = position; CGFloat r=(_endPoint.x - _startPoint.x)*(_endPoint.x - _startPoint.x)+(_endPoint.y - _startPoint.y)*(_endPoint.y - _startPoint.y); rid=sqrtf(r); } } - (void)draw:(CGContextRef)context { [super draw:context]; CGRect rect = CGRectMake(_startPoint.x-rid, _startPoint.y-rid,rid*2,rid*2); CGContextAddEllipseInRect(context, rect); CGContextDrawPath(context, kCGPathEOFillStroke); } @end