java—如何在装饰器设计模式中使用所有类?

o3imoua4  于 2021-07-07  发布在  Java
关注(0)|答案(2)|浏览(353)

所以我用java实现decorator设计模式。
总的来说,我有这个电话是正确的。

CrewMember crewMember = new Captain(new ChiefEngineer(new CrewMemberImpl()));

现在我有一个问题,我怎么能调用一个方法作为 crewMemberChiefEngineer 例如(不在基本接口中)。
理想情况下我想要的是:

crewMember.methodFromChiefEngineerClass();

也许有办法从船员那里得到所有相关的分类?以某种方式使用instanceof?还是我弄错了

vsmadaxz

vsmadaxz1#

Captain 类来获取 ChiefEngineer 对象并使用它来调用 ChiefEngineer 班级。

public class Captain {

  private final ChiefEngineer engineer;

  public Captain(final ChiefEngineer engineer) {
    this.engineer = engineer;
  } 

  public ChiefEngineer getChiefEngineer() {
    return this.engineer;
  }
}

那就做吧

crewMember.getChiefEngineer().methodFromChiefEngineerClass();
gr8qqesn

gr8qqesn2#

在中创建代理方法 Captain 调用包含的 ChiefEngineer 对象。

public class Captain {
    private final ChiefEngineer chiefEngineer;

    public Captain(final ChiefEngineer chiefEngineer) {
        this.chiefEngineer = chiefEngineer;
    }

    public void methodFromChiefEngineerClass() {
        chiefEngineer.methodFromChiefEngineerClass();
    }

}

相关问题