Last active
June 21, 2023 05:26
-
-
Save janodev/5220891 to your computer and use it in GitHub Desktop.
Objective-C Builder pattern.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
int main(int argc, char *argv[]) { | |
@autoreleasepool { | |
NutritionFacts *facts = [NutritionFacts new]; | |
// builder | |
facts = [[[[facts builder] calories:100] sodium:35] build]; | |
// bean constructor pattern | |
facts.calories=100; | |
facts.sodium=35; | |
// telescoping constructor pattern | |
// [[NutritionFacts alloc] initWithCalories:100]; | |
// [[NutritionFacts alloc] initWithCalories:100 sodium:35]; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@interface NutritionFacts(Builder) | |
-(NutritionFactsBuilder*)builder; | |
@end | |
@implementation NutritionFacts(Builder) | |
-(NutritionFactsBuilder*)builder { | |
return [[NutritionFactsBuilder alloc]initWithNutritionFacts:self]; | |
} | |
@end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@interface NutritionFacts : NSObject | |
@property (nonatomic, assign) NSUInteger calories, carbohydrate, | |
cholesterol, fat, fiber, protein, saturatedFat, sodium; | |
@end | |
@implementation NutritionFacts | |
@end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@interface NutritionFactsBuilder : NSObject | |
-(id)initWithNutritionFacts:(NutritionFacts*)facts; | |
@end | |
@implementation NutritionFactsBuilder { | |
NutritionFacts *_facts; | |
} | |
-(id)initWithNutritionFacts:(NutritionFacts*)facts { | |
self = [super init]; | |
if (self){ | |
_facts = facts; | |
} | |
return self; | |
} | |
-(BOOL)isValid { | |
// ... check valid ivar combos | |
NSAssert(YES,@"Always valid"); | |
} | |
-(NutritionFacts*)build { | |
[self isValid]; | |
return _facts; | |
} | |
-(instancetype)calories:(NSUInteger)calories { | |
_facts.calories = calories; | |
return self; | |
} | |
-(instancetype)sodium:(NSUInteger)sodium { | |
_facts.sodium = sodium; | |
return self; | |
} | |
// ... | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment