简体   繁体   中英

How to get all classes used in decorator design pattern?

So I'm implementing decorator design patter in java.

Overall I have this call which works correctly.

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

Now I have a question, how could I call a method as a crewMember from ChiefEngineer for example(which is not in the base interface).

What I would want ideally:

crewMember.methodFromChiefEngineerClass();

Maybe there is a way to get all related classed from crewMember? Using instanceof somehow? Or am I getting it wrong

Create a method in the Captain class to get the ChiefEngineer object and use that to call methods inside the ChiefEngineer class.

public class Captain {

  private final ChiefEngineer engineer;

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

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

Then do

crewMember.getChiefEngineer().methodFromChiefEngineerClass();

Create a proxy-method in Captain which calls the corresponding method of the contained ChiefEngineer object.

public class Captain {
    private final ChiefEngineer chiefEngineer;

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

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

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM