Improved decorator example.

This commit is contained in:
Ilkka Seppala 2014-12-06 14:35:18 +02:00
parent 10d4e3cadd
commit 9336284814

View File

@ -6,18 +6,23 @@ package com.iluwatar;
* class implements the same interface as the target and uses composition to * class implements the same interface as the target and uses composition to
* "decorate" calls to the target. * "decorate" calls to the target.
* *
* Using decorator pattern it is possible to change class behavior during
* runtime, as the example shows.
*
*/ */
public class App { public class App {
public static void main(String[] args) { public static void main(String[] args) {
// simple troll
System.out.println("A simple looking troll approaches."); System.out.println("A simple looking troll approaches.");
Hostile troll = new Troll(); Hostile troll = new Troll();
troll.attack(); troll.attack();
troll.fleeBattle(); troll.fleeBattle();
// change the behavior of the simple troll by adding a decorator
System.out.println("\nA smart looking troll surprises you."); System.out.println("\nA smart looking troll surprises you.");
Hostile smart = new SmartTroll(new Troll()); Hostile smart = new SmartTroll(troll);
smart.attack(); smart.attack();
smart.fleeBattle(); smart.fleeBattle();
} }