简体   繁体   中英

OOP: What should be the proper class design in this situation?

I have an object guiObject that comes from GUI. Based on its data fields I need to instantiate domainObject of proper class. It can either be DomainClassA or DomainClassB .

DomainClassA has one Integer contructor parameter intParamA (comes from guiObject.fieldA ).

DomainClassB has one Integer contructor parameter intParamB (comes from guiObject.fieldB ).

To solve this problem I made AbstractFactory that takes required fields from guiObject , instantiates either DomainClassAFactory or DomainClassBFactory with proper fields from GuiClass and retuns it. In turn, either of those factories create() properly instantiated domainObject .

But now, depending on guiObject.fieldC I need to alter intParamA and intParamB (ie decrease by 1) before instantiating domainObject . To achieve that I had to create separate factories for each different type of "parameter altering" for each DomainClass and then create separate abstract factories that produce correct factories. That sounds ugly and that looks ugly.

What should be the correct design?

Unless you need all those layers, have a factory that interrogates the guiObject and returns the right type.

Over-analyzing leads to way too much stuff that most apps simply don't need. Add additional layers of abstraction only if they're strictly necessary. They're usually not.

I'd personally put all this logic in the original factory rather than trying to spread it out so much:

public DomainObj getDomainObj(GuiObject guiObject) {
    int param = guiObject.someField ? guiObject.intParamA : guiObject.intParamB;
    param = guiObject.fieldC ? param : param - 1;
    return guiObject.someField ? new DomainClassA(param) : new DomainClassB(param);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM