【问题标题】:Passing an interface object in a constructor as an arguement在构造函数中传递接口对象作为参数
【发布时间】: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


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-12-12
      • 2016-07-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-29
      • 2012-11-14
      相关资源
      最近更新 更多