Created
April 25, 2015 20:49
-
-
Save mickeypash/526d8a618f62dde1ba46 to your computer and use it in GitHub Desktop.
Decorator pattern from AP 2015 Simon's example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// the first step is to define an abstract | |
// class that both BasicCar and our decorators will extend | |
public abstract class Car { | |
public abstract double getPrice(); | |
public abstract String getDescription(); | |
} | |
public class BasicCar extends Car{ | |
public double getPrice() { | |
return 10000; | |
} | |
public String getDescription() { | |
return "The basic car"; | |
} | |
} | |
// Decorators will add functionality to this | |
// by implementing these methods slightly differently | |
public abstract CarDecorator extends Car { | |
protected Car decoratedCar; | |
public CarDecorator(Car decoratedCar) { | |
this.decoratedCar = decoratedCar; | |
} | |
public double getPrice() { | |
return decoratedCar.getPrice(); | |
} | |
public String getDescription() { | |
return decoratedCar.getDescription(); | |
} | |
} | |
// add Alloys to the basic car | |
public class AlloyDecorator extends CarDecorator { | |
public AlloyDecorator(Car decoratedCar){ | |
super(decoratedCar); | |
} | |
public Double getPrice() { | |
return super.getPrice() + 250; | |
} | |
public String getDescription() { | |
return super.getDescription() + " + Alloys"; | |
} | |
} | |
// add CD Player to the basic car | |
public class CDDecorator extends CarDecorator { | |
public CDDecorator (Car decoratedCar) { | |
super(decoratedCar); | |
} | |
public Double getPrice() { | |
return super.getPrice() + 150; | |
} | |
public String getDescription() { | |
return super.getDescription() + " + CD Player" | |
} | |
} | |
public class DecoratorTest { | |
public static void main(String args) { | |
Car base = new BasicCar(); | |
System.out.println("Car costs " + base.getPrice() + " and has " + base.getDescription()); | |
Car alloys = new AlloyDecorator(new BasicCar()); | |
System.out.println("Car cost " + alloys.getPrice() + " and has " + alloys.getDescription()); | |
Car cd = new CDDecorator(new BasicCar()); | |
System.out.println("Car costs " + cd.getPrice() + " and has " + cd.getDescription()); | |
Car all = new CDDecorator(new AlloyDecorator (new BasicCar())); | |
System.out.println("Car costs " + all.getPrice() + " and has " + cd.getDescription()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment