Home > Back-end >  Best way to choose different child class to create new instance based on a boolean
Best way to choose different child class to create new instance based on a boolean

Time:06-30

Hi my question is simple.
I have 3 classes, BaseObject, and GoodObject BadObject that extends it:


public class BaseObject {
  // some properties
}

public class GoodObject extends BaseObject {
  // good properties
}

public class BadObject extends BaseObject {
  // bad properties
}

And in the code, I'll need to choose to create GoodObject or BadObject, depending on boolean value isGood:

public BaseObject businessLogic(){
  // ...
  return isGood ? new GoodObject(...) : new BadObject(...);
}

I don't like the idea for businessLogic to worry about which BaseObject instance to create, so plan to extract the return isGood ? new GoodObject(...) : new BadObject(...); into a factory class, so businessLogic will call something like Factory.createObject(isGood, ...). But not sure if there's a better or more elegant way.


An additional question, if I'm to use Factory class, what is the good way for me to pass in different properties? What I can think of is something similar to Builder pattern.

public class ObjectFactory {
  // all properties...

  public BaseObject withGoodProperties(good properties)   {
    // set good properties
    return this;
  }

  public BaseObject withBadProperties(bad properties)   {
    // set bad properties
    return this;
  }

  public BaseObject create(boolean isGood, base properties){
    return isGood ? new GoodObject(...) : new BadObject(...);
  }
}

Then in order to create a GoodObject i.e.: I need to call ObjectFactory.withGoodProperties(...).create(true, ...).
The problem is that it doesn't seem much simpler than the original
return isGood ? new GoodObject(...) : new BadObject(...);...

CodePudding user response:

I'd recommend going with the Factory approach, such as:

public class BaseObjectFactory {
    public static BaseObject create(boolean isGood) {
         return isGood ? new GoodObject(...) : new BadObject(...);
    }
}

If you want a Design Pattern approach. In my actual code, I'd probably have an if statement somewhere, and not be too concerned with this.

  • Related