如何从控制类中分离实体类
问题描述:
假设我的实体类实现了一个接口。如何让我的控件类使用该接口,以便控件类可以将该接口实例化为对象。如何从控制类中分离实体类
起初,我会用我的控制类实例化实体类的一个实例。但是,我想通过使用接口来解耦它们。
答
一个做到这一点的方法之一是使用静态工厂方法来创建并返回EntityInterface
引用。看到这个基本的例子:
EntityInterface entity = EntityFactory.getEntity();
有了这样定义的类型:
class EntityFactory {
public static EntityInterface getEntity() {
return new Entity();
}
}
interface EntityInterface {
}
class Entity implements EntityInterface {
}
答
好像Abstract Factory设计模式可以帮助这里。
使用定义通用实体工厂的接口。一旦你的控制类有一个工厂实例(作为接口),它可以调用它的createEntity()方法来创建特定的实体实例。
答
您可以使用静态工厂方法来完成这项
样品实施
public class ModelFactory implements ModelInterface{
public static ModelInterface getNewInstance() {
return new Model();
}
}
public interface ModelInterface {
}
public class Model implements ModelInterface{
}
现在
在控制类
ModelInterface object = ModelFactory.getNewInstance();