装饰图案出现问题

xxlali

我正在尝试学习装饰器模式,但有问题。

首先我有一个界面

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,返回的F1DecooratorCar构造函数feature1在原始上设置car1这辆新装饰的汽车被分配给了car1

但是,当您car1再次用装饰F2Decorator,您是在装饰而F1Decorator不是原始的Car您正在设置F1Decoratorfeature2,而不是原始Carfeature2因此,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] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章