定义:将一个产品的内部表象与产品的生成过程分割开来,从而可以使一个建造过程生成具有不同的内部表象的产品对象。
类型:对象创建
类图:
#import <Foundation/Foundation.h>
@interface Character : NSObject @property(nonatomic, assign)float protection; @property(nonatomic, assign)float power; @property(nonatomic, assign)float strength; @property(nonatomic, assign)float stamina; @property(nonatomic, assign)float intelligence; @property(nonatomic, assign)float agility; @property(nonatomic, assign)float aggressiveness; @end
#import "Character.h" @implementation Character - (instancetype)init{ if (self = [super init]) { _protection = 1.0; _power = 1.0; _strength = 1.0; _stamina = 1.0; _intelligence = 1.0; _agility = 1.0; _aggressiveness = 1.0; } return self; } @end
#import <Foundation/Foundation.h> #import "Character.h" @interface CharacterBuilder : NSObject{ Character * _character; } @property(nonatomic, readonly)Character *character; - (CharacterBuilder *)buildNewCharacter; - (CharacterBuilder *)builStrength:(float)value; @end
#import "CharacterBuilder.h" @implementation CharacterBuilder - (CharacterBuilder *)buildNewCharacter{ _character = [[Character alloc]init]; return self; } - (CharacterBuilder *)builStrength:(float)value{ _character.strength = value; return self; } @end
#import "CharacterBuilder.h" @interface StandardCharacterBuilder : CharacterBuilder @end
#import "StandardCharacterBuilder.h" @implementation StandardCharacterBuilder - (CharacterBuilder *)builStrength:(float)value{ _character.protection = value; _character.power = value; return [super builStrength:value]; } @end
#import <Foundation/Foundation.h> #import "StandardCharacterBuilder.h" @interface ChasingGame : NSObject - (Character *)createPlayer:(CharacterBuilder *)builder; - (Character *)createEnemy:(CharacterBuilder *)builder; @end
#import "ChasingGame.h" @implementation ChasingGame - (Character *)createPlayer:(CharacterBuilder *)builder{ [builder buildNewCharacter]; [builder builStrength:50.0]; return [builder character]; } - (Character *)createEnemy:(CharacterBuilder *)builder{ [builder buildNewCharacter]; [builder builStrength:80.0]; return [builder character]; } @end