Thomas Darimont
Erfahrenes Mitglied
Hallo,
dieser Beitrag erklärt das Strukturelle Muster: Decorator
Ausgabe:
Gruß Tom
dieser Beitrag erklärt das Strukturelle Muster: Decorator
Java:
package de.tutorials.design.patterns.structural;
import org.jpatterns.gof.DecoratorPattern.ConcreteDecorator;
import org.jpatterns.gof.DecoratorPattern.Decorator;
public class DecoratorExample {
public static void main(String[] args) {
WrappableWithClothes human = new Jacket(new Pullover(new TShirt(new Undershirt(new Human(36.0)))));
System.out.println("Human Body Temperature: " + human.getTemperature());
}
static class Human implements WrappableWithClothes{
private double temperature;
public Human(double temperature) {
this.temperature = temperature;
}
public double getTemperature() {
return temperature;
}
}
static interface WrappableWithClothes{
double getTemperature();
}
@Decorator
static abstract class Clothing implements WrappableWithClothes{
protected WrappableWithClothes wrappable;
public Clothing(WrappableWithClothes wrappable) {
this.wrappable = wrappable;
}
public double getTemperature(){
return wrappable.getTemperature() + getTemperatureContribution();
}
public double getTemperatureContribution(){
return 0.0;
}
}
@ConcreteDecorator
static class Undershirt extends Clothing {
public Undershirt(Human human) {
super(human); //naked
}
@Override
public double getTemperatureContribution() {
return super.getTemperatureContribution() + 0.05;
}
}
@ConcreteDecorator
static class TShirt extends Clothing {
public TShirt(Clothing beneath) {
super(beneath);
}
@Override
public double getTemperatureContribution() {
return super.getTemperatureContribution() + 0.1;
}
}
@ConcreteDecorator
static class Pullover extends Clothing {
public Pullover(Clothing beneath) {
super(beneath);
}
@Override
public double getTemperatureContribution() {
return super.getTemperatureContribution() + 0.2;
}
}
@ConcreteDecorator
static class Jacket extends Clothing {
public Jacket(Clothing beneath) {
super(beneath);
}
@Override
public double getTemperatureContribution() {
return super.getTemperatureContribution() + 0.5;
}
}
}
Ausgabe:
Code:
Human Body Temperature: 36.85
Gruß Tom