请参阅下面的代码。我看不出哪里出错了。我也很困惑!非常感谢任何帮助!
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;
}
}
答案 0 :(得分:3)
这里:
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
抽象并从中继承每个特定的装饰器。
答案 1 :(得分:0)
问题是你实际上并没有装饰任何东西。也就是说,你不是用装饰器“包装”一个组件。
的示例这种模式的一个很好的例子在书中:Head First Design Patterns。我非常喜欢这本书,如果你还没有这本书,我强烈推荐它。