我正在尝试学习装饰器模式,但有问题。
首先我有一个界面
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没有任何影响。我的设计有什么问题。如果可以的话,我想我会非常了解装饰器模式。
car1
用装饰时F1Decorator
,返回的F1Decoorator
是Car
。构造函数feature1
在原始上设置car1
。这辆新装饰的汽车被分配给了car1
。
但是,当您car1
再次用装饰时F2Decorator
,您是在装饰而F1Decorator
不是原始的Car
。您正在设置F1Decorator
的feature2
,而不是原始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
:
public F2Decorator(Car car) {
super(car);
decoratedCar.setFeature2(true);
}
经过这些更改,现在的输出为:
Price: 20000
Price: 21000
Price: 23000
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句