【发布时间】:2015-03-03 21:15:20
【问题描述】:
我正在尝试学习装饰器模式,但遇到了问题。
首先我有一个界面
public interface MyCar {
public String getMessage(int speed);
public int getPrice();
}
我是这样实现这个类的;
public class Car implements MyCar{
protected int price;
protected boolean feature1;
protected boolean feature2;
public Car(){
this.price = 0;
this.feature1 = false;
this.feature2 = false;
}
publicCar(int price){
this.price = price;
this.feature1 = false;
this.feature2 = false;
}
int getPrice(){
return price + (feature1 ? 1000 : 0) + (feature2 ? 2000 : 0);
}
}
之后我从这个类派生了两辆汽车
public class Car1 extends Car{
private static int price = 20000;
public Car1() {
super(price);
}
}
Car2 等级完全一样,只是价格是 30000。
在此之后,我创建了一个汽车装饰器类;
public abstract class CarDecorator extends Car {
protected Car decoratedCar;
public CarDecorator(){
decoratedCar = new Car();
}
public CarDecorator(Car decoratedCar) {
this.decoratedCar = decoratedCar;
}
public int getPrice(){
return this.decoratedCar.getPrice();
}
}
最后我创建了 2 个从 CarDecorator 派生的装饰器类:
public class F1Decorator extends CarDecorator{
public F1Decorator(Car car) {
super(car);
decoratedCar.feature1 = true;
}
}
public class F2Decorator extends CarDecorator{
public F2Decorator(Car car) {
super(car);
decoratedCar.feature2 = true;
}
}
public class Test {
public static void main(String[] args){
Car car1 = new Car1();
System.out.println("Price: " + car1.getPrice());
car1 = new F1Decorator(car1);
System.out.println("Price: " + car1.getPrice());
car1 = new F2Decorator(car1);
System.out.println("Price: " + car1.getPrice());
}
}
输出是
Price: 20000
Price: 21000
Price: 21000
为什么 feature2 对 car1 没有任何影响。我的设计有什么问题。如果你能帮忙,我想我会非常了解装饰器模式。
【问题讨论】:
-
我没有看到
feature2在getPrice方法中使用。也许应该在那里使用它。 -
抱歉错字。我已经编辑过了。只是复制粘贴错误。问题仍然存在。
标签: java design-patterns