mardi 3 mars 2015

Trouble with decorator pattern

I am trying to learn decorator pattern and I have problem with it.


Firstly I have an interface



public interface MyCar {
public String getMessage(int speed);
public int getPrice();
}


I implemented this class like this;



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) + (feature1 ? 2000 : 0);
}
}


After that I derived two cars from this class like



public class Car1 extends Car{
private static int price = 20000;

public Car1() {
super(price);
}
}


Car2 class is exactly the same except from price which is 30000.


After this point I created a car decorator class which is;



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();
}
}


Finally I have created 2 decorater class derived from 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());
}
}


And the output is



Price: 20000
Price: 21000
Price: 21000


Why feature2 does not have any effect on car1. What is wrong with my design. If you can help, I guess I will understand decorator pattern very well.


Aucun commentaire:

Enregistrer un commentaire