Simple Factory vs Factory Method: Switch statement in factory vs. client

好久不见. 提交于 2019-12-04 08:16:35

The standard Abstract Factory design pattern doesn't help?
Simplified Java code:

public interface IFactory {
    IObject createObject();
}

public class FactoryA implements IFactory {
    public IObject createObject() {
        return new ObjectA();
    }
}

public class FactoryB implements IFactory {
    public IObject createObject() {
        return new ObjectB();
    }
}

Client is configured (injected) with the needed Factory at run-time
    IFactory myFactory = ...   // new FactoryA();
...
IObject  myObject = myFactory.createObject();
...

See also the GoF Design Patterns Memory / Abstract Factory at http://w3sdesign.com.

VARIANT 2
Instead of using enum object types, define your object types with polymorphism (to avoid switch statements). Simplified Java code:

public interface IObjectType {
    int getObjectType();
    IObject createObject();
}

public class ObjectTypeA implements IObjectType {
    ...
    public IObject createObject() {
        return new ObjectA();
    }
}

public class ObjectTypeB implements IObjectType {
    ...
    public IObject createObject() {
        return new ObjectB();
    }
}

Client determines object type 
IObjectType myObjectType = ...   // new ObjectTypeA();
...
IObject  myObject = myObjectType.createObject();
...

My conclusion:
I think, a better solution would be to design your types with polymorphism instead of using enum constans. This would avoid switch statements and wouldn't violate the Open/Closed Principle on either the client or factory side.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!