/** * The Decorator pattern is a more flexible alternative to subclassing. The Decorator class * implements the same interface as the target and uses composition to "decorate" calls to the * target. Using the Decorator pattern it is possible to change the behavior of the class during * runtime. Decorator模式是子类的一种更灵活的替代方法。 Decorator类实现与目标相同的接口,并使用组合“修饰”对目标的调用。 使用Decorator模式,可以在运行时更改类的行为。 * * <p>In this example we show how the simple {@link SimpleTroll} first attacks and then flees the * battle. Then we decorate the {@link SimpleTroll} with a {@link ClubbedTroll} and perform the * attack again. You can see how the behavior changes after the decoration. <p>在此示例中,我们显示了简单的{@link SimpleTroll}如何首先攻击然后逃离战斗。 然后,我们用{@link ClubbedTroll}装饰{@link SimpleTroll},然后再次执行攻击。 您可以看到装饰后行为如何变化。 */ publicclassApp{
/** * Program entry point. * * @param args command line args */ publicstaticvoidmain(String[] args){
// simple troll LOGGER.info("A simple looking troll approaches."); var troll = new SimpleTroll(); troll.attack(); troll.fleeBattle(); LOGGER.info("Simple troll power {}.\n", troll.getAttackPower());
// change the behavior of the simple troll by adding a decorator LOGGER.info("A troll with huge club surprises you."); var clubbedTroll = new ClubbedTroll(troll); clubbedTroll.attack(); clubbedTroll.fleeBattle(); LOGGER.info("Clubbed troll power {}.\n", clubbedTroll.getAttackPower()); } }
publicTransactionAwareCacheDecorator(Cache targetCache){ Assert.notNull(targetCache, "Target Cache must not be null"); this.targetCache = targetCache; }
public <T> T get(Object key, Class<T> type){ returnthis.targetCache.get(key, type); }