gpt4 book ai didi

java - 在构造函数中将接口(interface)对象作为参数传递

转载 作者:行者123 更新时间:2023-11-30 08:04:06 25 4
gpt4 key购买 nike

如何将接口(interface)对象作为具体类中的参数传递?

我正在创建一个狐狸吃兔子的动物模拟器。狐狸和兔子有繁殖的能力。而且这两种动物也都具有老死的能力。这就是我正在创造的,这就是概念。

我想在 Simulator 类中传递一个工厂对象作为参数,以便将来可以轻松创建更多类型的工厂。例如,一个 VirusFactory,病毒可以杀死动物并随时间繁殖……等等。

所以接口(interface)工厂类看起来是这样的:

public interface Factory
{
//currently empty
}

AnimalFactory 具体类创建动物!。它实现了工厂接口(interface)。

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();
}
}

提前致谢

最佳答案

将参数声明为接口(interface)类型的构造函数或方法是完全可以接受的。事实上,这是一个很好的做法。

    public Simulator(Factory theFactory){
this.factory = theFactory;
this(DEFAULT_DEPTH, DEFAULT_WIDTH);
sane();
}

在这种情况下,您应该在类中将 animalFactory 属性声明为 Factory 类型:

    // A factory for creating actors - unused as yet.
private final Factory factory;

最后,创建一个 Simulator 的实例,将所选的工厂类型实例传递给构造函数:

Simulator simulator = new Simulator(new AnimalFactory());

关于java - 在构造函数中将接口(interface)对象作为参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35921056/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com