1

请看下面的代码。我看不出哪里出错了。我也很迷茫!非常感谢任何帮助!

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;
}
}
4

2 回答 2

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抽象并从中继承每个特定的装饰器。

于 2012-05-14T15:37:49.267 回答
0

问题是你实际上并没有装饰任何东西。也就是说,您不是用装饰器“包装”组件。

这是装饰器模式的示例。

这种模式的一个很好的例子在书中:Head First Design Patterns。我真的很喜欢这本书,如果你还没有,我强烈推荐它。

于 2012-05-14T14:46:09.653 回答