vendredi 26 février 2016

Understanding Decorator Pattern

This pattern is used to modify the functionality of an object at runtime without using inheritance or composition:

public interface Car {
   public void assemble();
}

    public class BasicCar implements Car {
@Override
public void assemble() {
System.out.print("Basic Car.");
}
}



 public class CarDecorator implements Car {
protected Car car;
public CarDecorator(Car c){
this.car=c;
}
@Override
public void assemble() {
this.car.assemble();
}
}

public class SportsCar extends CarDecorator {
public SportsCar(Car c) {
super(c);
}
@Override
public void assemble(){
car.assemble();
System.out.print(" Adding features of Sports Car.");
}
}

public class LuxuryCar extends CarDecorator {
public LuxuryCar(Car c) {
super(c);
}
@Override
public void assemble(){
car.assemble();
System.out.print(" Adding features of Luxury Car.");
}
}

public class DecoratorPatternTest {
public static void main(String[] args) {
Car sportsCar = new SportsCar(new BasicCar());
sportsCar.assemble();          //1                           
System.out.println("\n*****");
Car sportsLuxuryCar = new SportsCar(new LuxuryCar(new BasicCar()));
sportsLuxuryCar.assemble();   //2
}
}

output is:

Basic Car. Adding features of Sports Car.


Basic Car. Adding features of Luxury Car. Adding features of Sports Car.

because:

//1
@Override
    public void assemble(){
    car.assemble();                                        --> Basic Car.
    System.out.print(" Adding features of Sports Car.");   --> Adding features of Sports Car.

//2
@Override
    public void assemble(){
    car.assemble();                  --> LuxuryCar   -->   Basic Car.
    System.out.print(" Adding features of Sports Car.");   --> Adding features of Sports Car.

Also in CarDecorator if you comment this.car.assemble(); you get the same result because it is not used we don't have an istance of CarDecorator in the test class.

Am I right?

Aucun commentaire:

Enregistrer un commentaire