Multiple subclasses, how to instance any of them?

ε祈祈猫儿з 提交于 2019-12-05 16:35:15

The factory pattern is probably the way to go. If you store the fully qualified name in the DB then you can create a factory that reads the value and instantiates a new Item using the following:

Item item = (Item) Class.forName(theDBField).newInstance();
item.setName(name);
item.setDescription(desc);

Which means a much more concise factory that doesn't have to know about all the classes it can build. I really dislike having to update a factory everytime I add a new implementation and this is a simple way to avoid it.

to do this you will have to add getters and setters to the item interface.

In your case I would use a Factory method pattern (aka Factory pattern).

Factory method pattern is a creational pattern. The creational patterns abstract the object instantiation process by hiding how the objects are created and make the system independent of the object creation process.

Lets try to implement how it should work:

Model

public abstract class Model {  
   protected abstract void init();
}

Book

public class Book extends Model {
 @Override
protected void init() {
    System.out.println("I'm a Book");
}
}

Ball

public class Ball extends Model {
    @Override
protected void init() {
    System.out.println("I'm a Ball");
}
}

DbModelFactory

public abstract class DbModelFactory {
    public abstract Model getModel(int modelId);
}

SimpleDbModelFactory

public class SimpleDbModelFactory extends DbModelFactory  {

    @Override
    public Model getModel(int modelId) {
        Model model = null;
        if(modelId == Const.MODEL_BOOK) {

            model = new Book();
        }
        else if(modelId == Const.MODEL_BALL) {

            model = new Ball();
        }
        else {// throw Exception

        }
        return model;
    }
}

Const

public class Const {
    public static final int MODEL_BOOK = 0;
    public static final int MODEL_BALL = 1;
}

Launcher

public class Launcher {
  public static void main(String[] args) {
    DbModelFactory factory  = new SimpleDbModelFactory();
    Model book = factory.getModel(0);
    book.init(); // I'm a Book

    Model ball = factory.getModel(1);
    ball.init(); //I'm a Ball
    }
}

Factory pattern returns one of the several product subclasses. You should use a factory pattern If you have a super class and a number of subclasses and based on some data provided, you have to return the object of one of the subclasses

Now we have 2 Models book and ball and we don't care that both are actually Model.

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