-4

我在面试中被问到了以下问题,我很想知道答案。

我有一个由 Generator 扩展的基类“GeneratorBaseClass”。我被问到的问题是关于创建一个新的基类“GeneratorBaseClass2”并在运行时更改生成器以扩展它(无需更改生成器)。所以,作为代码的一个例子

public class GeneratorBase1 {
    public GeneratorBase1(){
        System.out.println("Generator Base 1 is used");
    }
}

public class Generator  extends  GeneratorBase1{

    public Generator() {
        //will call the appropriate super class
    }
    public static void main(String[] args){
        Generator test=new Generator();


    }


}

我想让 Generator 在运行时选择一个新的 GeneratorBase,所以改为

public class GeneratorBase2 {
    public GeneratorBase2(){
        System.out.println("Generator Base 2 is used");
    }
}

Generator的形式可以改变,但不能每次基类改变时都改变。这是关于允许在运行时选择基类,我不想只更改“扩展......”部分

4

1 回答 1

5

我在这里尽我所能。这个问题虽然模棱两可。为什么有人要一次又一次地更改基类?这可能是因为基类提供的功能在运行时会发生变化。如果是这种情况,则有两种可能的情况。

  1. 基类应该是一个接口,仅此而已。

  2. 您应该在基类中组合不断变化的功能,并让实现在运行时更改,就像您的策略设计模式的工作方式一样。

于 2013-05-02T06:47:50.967 回答