如何将接口对象作为参数传递给具体类?
我正在创造一种动物模拟器,其中狐狸吃兔子。狐狸和兔子有能力繁殖。这两种动物也有老年死亡的能力。这就是我正在创造的东西,这就是概念。
我想在Simulator类中传递Factory对象作为参数,以便将来可以轻松创建更多类型的工厂。例如,VirusFactory病毒可以杀死动物并随着时间的推移而繁殖......等等。
所以Interface Factory类看起来像这样:
public interface Factory
{
//currently empty
}
AnimalFactory具体类创建动物!它实现了Factory接口。
public class AnimalFactory implements Factory
{
//Code omitted
}
我有一个模拟器类。在模拟器类中,我想将Factory对象作为参数传递给Simulator构造函数。怎么办呢?
public class Simulator
{
// Constants representing configuration information for the simulation.
// The default width for the grid.
private static final int DEFAULT_WIDTH = 100;
// The default depth of the grid.
private static final int DEFAULT_DEPTH = 100;
// List of actors in the field.
private final List<Actor> actors;
// The current state of the field.
private final Field field;
// The current step of the simulation.
private int step;
// A graphical view of the simulation.
private final SimulatorView view;
// A factory for creating actors - unused as yet.
private final AnimalFactory factory;
/**
* Construct a simulation field with default size.
*/
public Simulator()
{
this(DEFAULT_DEPTH, DEFAULT_WIDTH);
sane();
}
/**
* Create a simulation field with the given size.
* @param depth Depth of the field. Must be greater than zero.
* @param width Width of the field. Must be greater than zero.
*/
public Simulator(int depth, int width)
{
assert (width > 0 && depth > 0) :
"The dimensions are not greater than zero.";
actors = new ArrayList<Actor>();
field = new Field(depth, width);
// Create a view of the state of each location in the field.
view = new SimulatorView(depth, width);
factory.setupColors(view);
// Setup a valid starting point.
reset();
sane();
}
}
提前致谢
答案 0 :(得分:3)
将构造函数或方法的参数声明为接口类型是完全可以接受的。事实上,这是一个很好的做法。
public Simulator(Factory theFactory){
this.factory = theFactory;
this(DEFAULT_DEPTH, DEFAULT_WIDTH);
sane();
}
在这种情况下,您应该在类中声明animalFactory属性为类型:
// A factory for creating actors - unused as yet.
private final Factory factory;
最后,创建一个Simulator
实例,将选定的工厂类型实例传递给构造函数:
Simulator simulator = new Simulator(new AnimalFactory());