IOS Design Pattern Learning Record (2) --- prototype Pattern

Source: Internet
Author: User

Definition of prototype mode

Prototype is the pattern applied to the copy operation. This pattern is initially defined in design patterns (Addison-Wesley, 1994 ), it defines "using a prototype instance to specify the type of the object to be created, and creating a new object by copying this prototype ". A simple understanding is to create a new object based on this prototype. This kind of creation refers to deep replication to get a new memory resource, rather than a new pointer reference. Use a prototype instance to specify the type of the object to be created, and copy the prototype to create a new object.

 

When the composition of a class is complex, such as containing multiple components or multiple custom class attributes, directly copying the current object is much easier than creating an object from the beginning, the prototype mode is the most suitable. Or there is little difference between objects. You can also use the prototype mode when several attributes are different, provided that you inherit the same parent class.

 

Applicable Environment

 

Objects to be created must be independent of their types and creation methods.

The class to be instantiated is determined at runtime.

Do not want the factory level that corresponds to the product level.

The differences between instances of different classes are only several combinations of States. (Copying the corresponding number of prototypes is more convenient than manual instantiation)

Class is not easy to create. (It is easier to copy existing composite objects and modify copies)

 

 

Knowledge mainly involved: copy and copy

 

For more information about deep copy and shallow copy (deep Copy & shallow copy), refer to the deep copy and shallow copy learning records in iOS in my blog.

 

 

Let's take an example. First, we need to create some fake data to make the fake data look like a lot. It seems difficult to create such an item, load to the ViewControllview we want to operate

 

Create a false data Person class

 

Point H file

 

// PersonItem. h // prototype mode CSDN /// Created by Wang yanlong on 13-12-30. // Copyright (c) 2013 longyan. all rights reserved. // # import
 
  
@ Interface PersonItem: NSObject
  
   
@ Property (nonatomic, strong) UIImage * headerImg; // Avatar @ property (nonatomic, assign) int age; // age @ property (nonatomic, assign) CGFloat height; // height @ property (nonatomic, assign) CGFloat weight; // weight @ property (nonatomic, assign) int numID; // student ID @ property (nonatomic, assign) int classNum; // academic year @ property (nonatomic, assign) int score1; // Score 1 @ property (nonatomic, assign) int score2; // score 2 @ property (nonatomic, assign) int score3; // score 3 @ property (nonatomic, assign) int score4; // score 4 @ property (nonatomic, assign) int score0; // score 0 @ property (nonatomic, assign) BOOL isChoose; // determine whether it is selected @ end
  
 


 

 

Load fake data

 

-(BOOL) application :( UIApplication *) application didfinishlaunchingwitexceptions :( NSDictionary *) launchOptions {self. window = [[UIWindow alloc] initWithFrame: [[UIScreen mainScreen] bounds]; // Override point for customization after application launch. NSMutableArray * arr = [[NSMutableArray alloc] initWithCapacity: 0]; // create false data for (int I = 0; I <10; I ++) {PersonItem * item = [[PersonItem alloc] init]; item. headerImg = [UIImage imageNamed: [NSString stringWithFormat: @ % d, I + 1]; item. age = 15 + I; item. height = 165 + I; item. weight = 120 + I; item. numID = 100 + I; item. classNum = 10 + I; item. score0 = 100 + I; item. score1 = 90 + I; item. score2 = 80 + I; item. score3 = 70 + I; item. score4 = 60 + I; item. isChoose = NO; [arr addObject: item];} EditViewController * vc = [[EditViewController alloc] initWithItem: arr]; UINavigationController * nav = [[UINavigationController alloc] Priority: vc]; self. window. rootViewController = nav; self. window. backgroundColor = [UIColor whiteColor]; [self. window makeKeyAndVisible]; return YES ;}

Next, we drag a GMGridView and some image data to facilitate our presentation.

 

 

 

Enter the display page.

 

Let's assume that if we want to create a new data, but the data is similar to the previous one, there are some places to modify, such as modifying the profile picture, so what should we do? We can re-create a preson class item as in the first step.

 

 

PersonItem *item = [[PersonItem alloc]init];        item.headerImg = [UIImage imageNamed:[NSString stringWithFormat:@%d,i+1]];        item.age = 15+i;        item.height = 165+i;        item.weight = 120+i;        item.numID = 100+i;        item.classNum = 10+i;        item.score0 = 100+i;        item.score1 = 90+i;        item.score2 = 80+i;        item.score3 = 70+i;        item.score4 = 60+i;        item.isChoose = NO;

However, if we create 100 and 1000, it is not reasonable to do so. In this case, we will use our prototype.

 

Let's talk about the definition of the prototype mode again:When the composition of a class is complex, such as containing multiple components or multiple custom class attributes, directly copying the current object is much easier than creating an object from the beginning, the prototype mode is the most suitable.

 

Here, I will not write about the initialization and some modifications of GMGridView. It is very simple. Focus on the three button methods.

 

 

# Pragma bottomView method // method of incorrect copy-(void) errorItem {if (self. chooseArr. count = 0) {return;} PersonItem * item = [self. chooseArr objectAtIndex: 0]; item. headerImg = [UIImage imageNamed: @ 15]; [self. selectedItems addObject: item]; [self. gridView reloadData];} // Method for correct copying-(void) copyItem {if (self. chooseArr. count = 0) {return;} PersonItem * itemNew = [[self. chooseArr objectAtIndex: 0] copy]; itemNew. headerImg = [UIImage imageNamed: @ 15]; [self. selectedItems addObject: itemNew]; [self. gridView reloadData];} // delete button-(void) delItem {if (self. chooseArr. count = 0) {return;} if (self. selectedItems. count <= 1) {return;} [self. selectedItems removeObject: [self. chooseArr objectAtIndex: 0]; [self. chooseArr removeAllObjects]; [self. gridView reloadData];}

If you click the incorrect COPY method, you will find

 

 

 

What do you find? You copied a new item, but the avatar of the old item also changed. Why? Let's take a look at the printer.

 

 

The two of them have the same memory address, that is to say, the Pointer Points to the same memory address, so if you modify A, B will naturally change, that is, the so-called shallow copy.

 

If you delete them, you will find that they are all gone.

 

To avoid this method, we need to implement deep copy for the person class, so we need to follow the NSCopying protocol. The Code is as follows:

 

# Import PersonItem. h @ implementation PersonItem // follow the NSCopying protocol and copy a new item-(id) copyWithZone :( NSZone *) zone {PersonItem * item = [[self class] allocWithZone: zone] init]; item. headerImg = [_ headerImg copy]; item. age = _ age; item. height = _ height; item. weight = _ weight; item. numID = _ numID; item. classNum = _ classNum; item. score0 = _ score0; item. score1 = _ score1; item. score2 = _ score2; item. score3 = _ score3; item. score4 = _ score4; return item;} @ end

In this way, if you select the correct copy, the result will be as follows:

 

 

The reason is that they have two different memory addresses, so the changes do not affect each other.

 

This is the prototype I understand. If you have any mistakes, I hope you can correct them.

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.