请看我的课。在其中创建了 WoW 头像。在构造方法中创建不同类的实例。如果程序被一个新的类(例如牛头人)扩展,构造方法必须愚蠢地改变。必须在方法中添加另一个对象实例化。这与开闭原则相矛盾,根据该原则,软件应该对扩展开放但对更改关闭。我该如何解决这个问题。
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);
}
}