有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java模板方法需要在子构造函数中声明一个对象

扩展母类的子类,该母类在其构造函数中调用注入子类中的模板方法,因为它需要在子构造函数中获得的值

我如何在不更改父构造函数的情况下执行类似操作(这里是Foo,我不能在真正的Foo类中执行任何更改):

public abstract class Foo{
    public Foo(){
        register();
    }

    public abstract void register();

    public void aMethod(int aValue){
        // body
    }

}

public class Bar extends Foo{

    public Foo(int aValue){
        // body
    }

    register(){
        aMethod(aValue);
    }
}

在这里,即使我把aValue放在一个字段中,aValue也不会被创建

aMethod(aValue);.

我怎样才能解决我的问题

我正在寻找任何模式,ULM,解决方案


共 (3) 个答案

  1. # 1 楼答案

    在构造函数中调用抽象方法是一种糟糕的设计。一些工具,比如PMD,默认情况下会将其指示为警告(甚至可能是错误)。所以我觉得这里很难谈论任何模式。我要做的是实现Bar类,如下所示

    public class Bar extends Foo{
    
        private int aValue;
        private boolean initialized = false;
    
    
        public Bar(int aValue){
            this.aValue = aValue;
            initialized = true;
            register();
        }
    
        public void register(){
           if (initialized)
           aMethod(aValue);
        }
    
    
    }
    
  2. # 2 楼答案

    a child class extending a mother class which, in its constructor call a template method instianted in the child class because it need a value obtained in the child constructor.

    为什么子类构造函数不直接将值传递给超类构造函数呢

    public abstract class Foo {
        protected Foo(int value) {
           ... use value ...
       }
    }
    
    public class Bar extends Foo {
        public Foo(int value) {
            super(value);
        }
        ...
    }
    

    请注意,在构造函数中调用虚拟方法是一种危险的做法,因为子类还没有机会初始化自己

  3. # 3 楼答案

    你的班级结构很混乱。您在遗留代码中有不能更改的内容吗?如果不改变它:-)