我有以下工厂班级:

public class MessagePresenterCreator implements IPresenterFactory{
    @Override
    public MessagePresenter createPresenter(Message m) {
        if (m instanceof Letter) {
            return new LetterPresenter();
        }
        if (m instanceof Cable) {
            return new CablePresenter();
        }
        if (m instanceof Postcard) {
            return new PostcardPresenter();
        }
        throw new IllegalArgumentException();
    }
}


我可以通过以下界面配置向导以自动生成并提供此类工厂:

public interface IPresenterFactory {
    public abstract MessagePresenter createPresenter(Message m);
}

最佳答案

没有向导没有像这样的工厂。您可以编写一个使用Map<Class<? extends Message>, Class<? extends MessagePresenter>并使用反射的工厂。这样,您便可以在guice模块中对其进行管理。

public class MessagePresenterCreator implements IPresenterFactory{
    private final Map<Class<? extends Message>, Class<? extends MessagePresenter> mapping;
    public MessagePresenterCreator(Map<Class<? extends Message>, Class<? extends MessagePresenter> mapping) {
         this.mapping = mapping;
    }

    @Override
    public MessagePresenter createPresenter(Message m) {
       Class<? extends MessagePresenter> clazz = mapping.get(m);
       if (clazz == null) {
           throw new UnsupportedOperationException();
       }
       return clazz.newInstance();
    }
}

10-01 18:38