design_patterns_in_typescript icon indicating copy to clipboard operation
design_patterns_in_typescript copied to clipboard

new approach for builder pattern

Open miladvafaeifard opened this issue 7 years ago • 5 comments

feel free to make suggestion and improvements based on the approach.

miladvafaeifard avatar Oct 16 '18 11:10 miladvafaeifard

@torokmark, have you checked my suggestion of the changes? :)

miladvafaeifard avatar Apr 13 '20 12:04 miladvafaeifard

Hi Milad,

Nice approach. Though, I am a bit concerned about the followings:

  1. Even though, Build interface is a general type with type param, it requires the implementor class to have setAge, setPhone, setAddress methods. What if I am intended to use Build with other type paramater like Car. I cannot use it, since it makes me implement setPhone in Car, but a car does not have phone number. In my point of view, Build is quite misleading in this way.

    Let me suggest the following.

    Let us have a Build interface with type parameter, and this interface has only one method, like build(): T

namespace BuilderPattern {
    export interface Builder<T> {
        build(): T;
    }

    // ...
}
  1. Director with UserBuilder parameter in its constuctor is a bit smelly in this way. Why does not makeUser return a User?

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()
    }
}

torokmark avatar Apr 13 '20 13:04 torokmark

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 avatar Jun 02 '20 20:06 miladvafaeifard

@miladvafaeifard , yes please, it would be great if you did refactoring on the approach.

I am always happy to see people contributing. Thank you

torokmark avatar Jun 15 '20 16:06 torokmark

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.

miladvafaeifard avatar Jul 13 '20 20:07 miladvafaeifard