设计模式-原型模式
效果:
原型模式,其实就是完整的复制一个对象,以一个对象为样本,进行复制作业,然后再来使用.
以下以复制一个UIView的操作来讲解原型模式的实现
注:UIView对象是不能够复制的,我们需要完整的把UIView对象的参数都复制了后,就行了.
http://stackoverflow.com/questions/4425939/can-uiview-be-copied
Your app probably crashes with something like:
[UIView copyWithZone:]: unrecognized selector sent to instance 0x1c6280
The reason is that UIView does not implement the copying protocol, and therefore there is no copyWithZone
selector in UIView.
因为UIView没有实现复制的协议,所以也就不能复制UIView了.
UIView+Prototype.h 与 UIView+Prototype.m
// // UIView+Prototype.m // Copy // // Created by YouXianMing on 14/11/14. // Copyright (c) 2014年 YouXianMing. All rights reserved. // #import "UIView+Prototype.h" @implementation UIView (Prototype) - (UIView *)createPrototype { UIView *prototypeView = nil; if (self) { // 创建出view prototypeView = [[UIView alloc] initWithFrame:self.frame]; // 被复制的内容 prototypeView.transform = self.transform; prototypeView.contentScaleFactor = self.contentScaleFactor; prototypeView.multipleTouchEnabled = self.multipleTouchEnabled; prototypeView.exclusiveTouch = self.exclusiveTouch; prototypeView.autoresizesSubviews = self.autoresizesSubviews; prototypeView.autoresizingMask = self.autoresizingMask; prototypeView.clipsToBounds = self.clipsToBounds; prototypeView.backgroundColor = self.backgroundColor; prototypeView.alpha = self.alpha; prototypeView.clearsContextBeforeDrawing = self.clearsContextBeforeDrawing; prototypeView.hidden = self.hidden; prototypeView.contentMode = self.contentMode; prototypeView.tintColor = self.tintColor; prototypeView.tintAdjustmentMode = self.tintAdjustmentMode; } return prototypeView; } @end
// // UIView+Prototype.h // Copy // // Created by YouXianMing on 14/11/14. // Copyright (c) 2014年 YouXianMing. All rights reserved. // #import <UIKit/UIKit.h> @interface UIView (Prototype) /** * 创建当前View的原型 * * @return 当前view的一个新的实例 */ - (UIView *)createPrototype; @end
使用:
// // ViewController.m // Copy // // Created by YouXianMing on 14/11/14. // Copyright (c) 2014年 YouXianMing. All rights reserved. // #import "ViewController.h" #import "UIView+Prototype.h" @interface ViewController () @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; // 作为原型的view UIView *redView = [[UIView alloc] initWithFrame:CGRectMake(50, 50, 100, 100)]; redView.backgroundColor = [UIColor redColor]; redView.alpha = 0.5; [self.view addSubview:redView]; // 根据一个原型创建出view UIView *greenView = [redView createPrototype]; greenView.frame = CGRectMake(75, 75, 100, 100); greenView.backgroundColor = [UIColor greenColor]; [self.view addSubview:greenView]; // 根据一个原型创建出view UIView *blueView = [greenView createPrototype]; blueView.frame = CGRectMake(100, 100, 100, 100); blueView.backgroundColor = [UIColor blueColor]; [self.view addSubview:blueView]; } @end
需要注意的地方: