OlexG / Patterns

Simples demos of various design patterns in javascript and typescript.
0 stars 0 forks source link

Object creators should probably be static? #3

Closed mattfbacon closed 3 years ago

mattfbacon commented 3 years ago

A function to create an instance doesn't really make sense as an instance method, unless that method makes a clone of the existing instance. Same is true if you are just going to take an instance of something else.

General rule: if you don't need access to instance-specific data, don't make it an instance method.

abstract class UserCreator {
    abstract createUser(): User

    printWelcomeMessage(user: User) {
        console.log(user.getWelcomeMessage());
    }
}

to

abstract class UserCreator {
    static abstract createUser(): User

    static printWelcomeMessage(user: User) {
        console.log(user.getWelcomeMessage());
    }
}

and

function someClientFunction(creator: UserCreator) {
    // is not aware of creator type
    const user = creator.createUser();
    creator.printWelcomeMessage(user);
}

someClientFunction(new AdminCreator());
someClientFunction(new CustomerCreator());

to

function someClientFunction(creator: typeof UserCreator) {
    // is not aware of creator type
    const user = creator.createUser();
    creator.printWelcomeMessage(user);
}

someClientFunction(AdminCreator);
someClientFunction(CustomerCreator);
mattfbacon commented 3 years ago

This applies to Creational/factoryMethod.ts

mattfbacon commented 3 years ago

The user is not static but the user creator is.

mattfbacon commented 3 years ago

If you want to have the creators depend on instance fields, then add instance fields to demonstrate this.

OlexG commented 3 years ago

just realized I can't do abstract static so sadly no static