design_patterns_in_typescript
design_patterns_in_typescript copied to clipboard
new approach for builder pattern
feel free to make suggestion and improvements based on the approach.
@torokmark, have you checked my suggestion of the changes? :)
Hi Milad,
Nice approach. Though, I am a bit concerned about the followings:
-
Even though,
Buildinterface is a general type with type param, it requires the implementor class to havesetAge,setPhone,setAddressmethods. What if I am intended to useBuildwith other type paramater likeCar. I cannot use it, since it makes me implementsetPhoneinCar, but a car does not have phone number. In my point of view,Buildis quite misleading in this way.Let me suggest the following.
Let us have a
Buildinterface with type parameter, and this interface has only one method, likebuild(): T
namespace BuilderPattern {
export interface Builder<T> {
build(): T;
}
// ...
}
DirectorwithUserBuilderparameter in its constuctor is a bit smelly in this way. Why does notmakeUserreturn aUser?
I would recommend the following here:
export class UserDirector implements Director<User> {
constructor(private userBuilder: UserBuilder){}
create(): User {
if(this.userBuilder.Name === 'Jancsi') {
this.userBuilder.setAge(12)
.setPhone("0123456789")
.setAddress("asdf");
} else {
this.userBuilder.setAge(0)
.setPhone("xxxxxxxxx")
.setAddress("xxxx");
}
return this.userBuilder.build()
}
}
Hi Mark 👋
Your approach makes much more sense to me, hence I completely agree on this. Shall i refactor with your approach in my next commit in this thread with a quick polish? 😃
@miladvafaeifard , yes please, it would be great if you did refactoring on the approach.
I am always happy to see people contributing. Thank you
Hi @torokmark,
I refactored and polished based on your suggestion. I would appreciate if you could review the change. and provide your thoughts on this.