gpt4 book ai didi

java - 无法使装饰器模式工作

转载 作者:行者123 更新时间:2023-11-29 05:59:52 25 4
gpt4 key购买 nike

请看下面的代码。我看不出哪里出错了。我也很困惑!非常感谢您的帮助!

package code;

public class Client {

public static void main(String[] args){

proxyPlane plane = new proxyPlane(new Pilot(18));
plane.flyPlane();

plane = new proxyPlane(new Pilot(25));
plane.flyPlane();

DecoratedPilot decPilot = new Pilot(35);

System.out.println("Experienced Pilot of age " + Pilot.Age() + " " + decPilot.getDecotation());
}

}


package code;

public interface DecoratedPilot {

public String getDecotation();
}


package code;

public class Decoration extends PilotDecorator {

public Decoration(Pilot pilot) {
super(pilot);
// TODO Auto-generated constructor stub
}

@Override
public String getDecotation() {
return "Pilot has earned his Commercial Wings";
}
}


package code;

public abstract class PilotDecorator implements DecoratedPilot {

public PilotDecorator(Pilot pilot)
{
apilot = pilot;
}
}


package code;

public class Pilot implements DecoratedPilot {

private static int age;

public static int Age() {

return age;
}

public Pilot(int age){

Pilot.age = age;
}

public String getDecotation() {
// TODO Auto-generated method stub
return null;
}
}

最佳答案

这里:


        package code;

public class Client {

public static void main(String[] args) {
// -- A standard pilot
Pilot standardPilot = new StandardPilot(35);
System.out.println("Pilot : " + standardPilot.getAge() + " - " + standardPilot.getDescription());
// -- A decorated pilot
Pilot decoratedPilot = new DecoratedPilot(standardPilot);
System.out.println("Pilot : " + decoratedPilot.getAge() + " - " + decoratedPilot.getDescription());
}
}

        package code;

public interface Pilot {
int getAge();
String getDescription();
}

    package code;

public class StandardPilot implements Pilot {

private int age;

public StandardPilot(int age) {
this.age = age;
}

@Override
public int getAge() {
return age;
}

@Override
public String getDescription() {
return "Standard Pilot";
}


package code;

public class DecoratedPilot implements Pilot {

private Pilot pilot;

public DecoratedPilot(Pilot pilot) {
// todo : check not null
this.pilot = pilot;
}

@Override
public int getAge() {
return pilot.getAge();
}

@Override
public String getDescription() {
return "Decorated Pilot";
}
}

如果您需要多个装饰器,您可以使 DecoratedPilot 抽象并从中继承每个特定的装饰器。

关于java - 无法使装饰器模式工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10585300/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com