Z.J
Z.J

Reputation: 349

Best Practice Open Close Principle

Please take a look at my class. In it WoW avatars are created. In the constructor method instances of different classes are created. If the program is extended by a new class (e.g. Tauren), the constructor method must be changed stupidly. One would have to add another object instantiation into the method. This contradicts the Open Close principle, according to which a software should be open for extensions but closed for changes. How can I solve this problem.

public class UpdateAvatarFactory{

    public UpdateAvatarFactory(Client client){
        ICreateMethod createHuman = new CreateHuman();
        createHuman.name="Human";
        ICreateMethod createElf = new CreateElf();
        createElf.name="Elf";
        ICreateMethod createGnome = new CreateGnome();
        createGnome.name="Gnome";
        ICreateMethod createOrc = new CreateOrc();
        createOrc.name="Orc";

        client.avatarFactory.addCreateMethod(createHuman);
        client.avatarFactory.addCreateMethod(createElf);
        client.avatarFactory.addCreateMethod(createGnome);
        client.avatarFactory.addCreateMethod(createOrc); 
    }

}

Upvotes: 0

Views: 35

Answers (1)

callOfCode
callOfCode

Reputation: 1026

In case you depicted, there is no point of having such class at all - it is the same as a static method. Avatar factory could be a private member of Client and could simply have a method which takes array of CreateWhatever (according to Law of Demeter).

Now how to prevent hardcoding all these new Create*()? In real world scenarios it is usually done by DI (dependency injection) libraries. They often comes with your framework of choice (e.g. Spring), but you can find standalone solutions too (I don't work with java for many years now, so I don't know the latest trends, but you can find them easily).

Upvotes: 0

Related Questions