【发布时间】:2016-03-10 15:44:35
【问题描述】:
如何将接口对象作为参数传递给具体类?
我正在创建一个狐狸吃兔子的动物模拟器。狐狸和兔子有繁殖能力。而且这两种动物也都具有老死的能力。所以这就是我正在创造的,这就是概念。
我想在 Simulator 类中传递一个 Factory 对象作为参数,以便将来可以轻松创建更多类型的工厂。例如,VirusFactory,病毒可以杀死动物并随着时间的推移繁殖......等等。
所以接口工厂类看起来像这样:
public interface Factory
{
//currently empty
}
AnimalFactory 具体类创建动物!。它实现了工厂接口。
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();
}
}
提前致谢
【问题讨论】:
标签: java object interface parameter-passing