Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
package pl.mperor.lab.java.design.pattern.structural.decorator.classic;

public interface Coffee {

int getCost();

default String getDescription() {
return this.getClass().getSimpleName();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
package pl.mperor.lab.java.design.pattern.structural.decorator.classic;

public abstract class CoffeeDecorator implements Coffee {

protected final Coffee coffee;
protected final int cost;

protected CoffeeDecorator(Coffee coffee, int cost) {
this.coffee = coffee;
this.cost = cost;
}

@Override
public int getCost() {
return coffee.getCost() + cost;
}

@Override
public String getDescription() {
return "%s + %s".formatted(coffee.getDescription(), Coffee.super.getDescription());
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package pl.mperor.lab.java.design.pattern.structural.decorator.classic;

public class NormalCoffee implements Coffee {

@Override
public int getCost() {
return 100;
}

@Override
public String getDescription() {
return "Coffee";
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
package pl.mperor.lab.java.design.pattern.structural.decorator.classic;

public class WithChocolate extends CoffeeDecorator {

public WithChocolate(Coffee coffee) {
super(coffee, 150);
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
package pl.mperor.lab.java.design.pattern.structural.decorator.classic;

public class WithMilk extends CoffeeDecorator {

public WithMilk(Coffee coffee) {
super(coffee, 50);
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
package pl.mperor.lab.java.design.pattern.structural.decorator.classic;

public class WithSugar extends CoffeeDecorator {

public WithSugar(Coffee coffee) {
super(coffee, 30);
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package pl.mperor.lab.java.design.pattern.structural.decorator.classic;

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

import java.util.stream.Stream;

public class CoffeeDecoratorTest {

@Test
public void shouldAllowToDynamicallyExtendCoffeeWithMilkChocolateOrSugar() {
NormalCoffee normal = new NormalCoffee();
Coffee robustCoffee = new WithChocolate(new WithMilk(new WithSugar(normal)));
Assertions.assertTrue(normal.getCost() < robustCoffee.getCost());
Assertions.assertTrue(Stream.of("WithChocolate", "WithSugar", "WithMilk")
.allMatch(robustCoffee.getDescription()::contains)
);
}

}
Loading