objective c - How to creating an immutable object along with a Builder pattern in ObjC? -


what struggling creating immutable object builder pattern in objc. have user object following properties:

  1. first name
  2. last name

to ensure immutability propose following code:

@protocol user @property (nonatomic, strong, readonly) nsstring *const firstname; @property (nonatomic, strong, readonly) nsstring *const lastname; @end  @interface user: nsobject<user> - (instancetype)initwithfirstname:(nsstring *)fname withlastname:(nsstring *)lname; @end  @implementation user @synthesize firstname; @synthesize lastname;  - (instancetype)initwithfirstname:(nsstring *)fname withlastname:(nsstring *)lname {     nsparameterassert(fname);     nsparameterassert(lname);     if (self = [super init]) {         self->firstname = [fname copy];         self->lastname = [lname copy];     }     return self; } @end 

what struggling how implement builder immutable object?

helpful links on builder:

the builder pattern in objc

builder pattern definiton

the link posted above uses 2 objects implement builder pattern. dedicated builder object subsequently passed create/build method returning object built. here contrived example of implement builder pattern immutable object.

first let's create immutable object; object built builder object.

@interface person: nsobject  @property (nonatomic, readonly) nsstring *firstname; @property (nonatomic, readonly) nsstring *lastname;  @end  @implementation person  - (instancetype)initwithfirstname:(nsstring *)firstname lastname:(nsstring *)lastname{       self = [super init]      if(!self) return nil;       _firstname = [firstname copy];      _lastname = [lastname copy];       return self;  }  @end 

now let's create builder object.

@interface personbuilder: nsobject  @property (nonatomic, strong) nsstring *firstname;  @property (nonatomic, strong) nsstring *lastname;  - (person *)create;  @end  @implementation personbuilder  - (person *)create{       return [[person alloc] initwithfirstname:self.firstname lastname:self.lastname];  }  @end 

implement classes

personbuilder *builder = [personbuilder new]; builder.firstname = "john"; builder.lastname = "doe";  person *john = [builder create]; 

in objective-c don't see reason implement builder pattern unless trying avoid long , confusing constructor signature or if object has 2 many properties or options such nsdatecomponent. builder pattern allows split initialization of complex immutable object multiple simple setter calls. create/build method implemented on builder gives hook point in can verify object being created want. use pattern in rare cases.


Comments

Popular posts from this blog

javascript - Using jquery append to add option values into a select element not working -

Android soft keyboard reverts to default keyboard on orientation change -

jquery - javascript onscroll fade same class but with different div -