我正在尝试学习装饰模式,但我遇到了问题。
首先我有一个界面
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的decorater类:
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没有任何影响。我的设计出了什么问题。如果你能提供帮助,我想我会非常了解装饰模式。
答案 0 :(得分:3)
当您使用car1
装饰F1Decorator
时,会返回F1Decoorator
,即Car
。构造函数在原始feature1
上设置car1
。这辆新装修的汽车被分配回car1
。
但是,当您使用car1
再次装饰F2Decorator
时,您正在装饰F1Decorator
,而不是原始Car
。您正在设置F1Decorator
的{{1}},而不是原始feature2
的{{1}}。因此,原始Car
上的feature2
仍为feature2
,价格仍为Car
。
介绍并调用false
上的方法以及将通过功能设置传递给21000
的装饰器类。
在Car
:
Car
在Car
:
public void setFeature1(boolean feat1)
{
this.feature1 = feat1;
}
public void setFeature2(boolean feat2)
{
this.feature2 = feat2;
}
在CarDecorator
:
public void setFeature1(boolean feat1)
{
this.decoratedCar.setFeature1(feat1);
}
public void setFeature2(boolean feat2)
{
this.decoratedCar.setFeature2(feat2);
}
在F1Decorator
:
public F1Decorator(Car car) {
super(car);
// Replace the assignment with this line.
decoratedCar.setFeature1(true);
}
通过这些更改,输出现在为:
F2Decorator