目的
动态地将附加职责附加到对象上。装饰器为扩展功能提供了一种灵活的子类替代方案。
说明
附近的山上有一个愤怒的巨魔。通常它是徒手但有时它有武器。为了武装巨魔,没有必要创造一个新的巨魔,可用合适的武器动态装饰它。
简而言之
Decorator模式允许您通过将对象包装在装饰器类的对象中来动态更改对象在运行时的行为。
维基百科说
在面向对象的编程中,装饰器模式是一种设计模式,它允许将行为静态或动态地添加到单个对象,而不会影响同一类中其他对象的行为。装饰器模式通常用于遵守单一责任原则,因为它允许在具有特定关注领域的类之间划分功能。
源码示例
让我们来看看巨魔的例子吧。首先,我们有一个简单的巨魔实现troll界面
<b>public</b> <b>interface</b> Troll { <b>void</b> attack(); <b>int</b> getAttackPower(); <b>void</b> fleeBattle(); } <b>public</b> <b>class</b> SimpleTroll implements Troll { <b>private</b> <b>static</b> <b>final</b> Logger LOGGER = LoggerFactory.getLogger(SimpleTroll.<b>class</b>); @Override <b>public</b> <b>void</b> attack() { LOGGER.info(<font>"The troll tries to grab you!"</font><font>); } @Override <b>public</b> <b>int</b> getAttackPower() { <b>return</b> 10; } @Override <b>public</b> <b>void</b> fleeBattle() { LOGGER.info(</font><font>"The troll shrieks in horror and runs away!"</font><font>); } } </font>
接下来我们想为巨魔添加俱乐部。我们可以使用装饰器动态地完成它
<b>public</b> <b>class</b> ClubbedTroll implements Troll { <b>private</b> <b>static</b> <b>final</b> Logger LOGGER = LoggerFactory.getLogger(ClubbedTroll.<b>class</b>); <b>private</b> Troll decorated; <b>public</b> ClubbedTroll(Troll decorated) { <b>this</b>.decorated = decorated; } @Override <b>public</b> <b>void</b> attack() { decorated.attack(); LOGGER.info(<font>"The troll swings at you with a club!"</font><font>); } @Override <b>public</b> <b>int</b> getAttackPower() { <b>return</b> decorated.getAttackPower() + 10; } @Override <b>public</b> <b>void</b> fleeBattle() { decorated.fleeBattle(); } } </font>
这是行动中的巨魔
<font><i>// simple troll</i></font><font> Troll troll = <b>new</b> SimpleTroll(); troll.attack(); </font><font><i>// The troll tries to grab you!</i></font><font> troll.fleeBattle(); </font><font><i>// The troll shrieks in horror and runs away!</i></font><font> </font><font><i>// change the behavior of the simple troll by adding a decorator</i></font><font> Troll clubbedTroll = <b>new</b> ClubbedTroll(troll); clubbedTroll.attack(); </font><font><i>// The troll tries to grab you! The troll swings at you with a club!</i></font><font> clubbedTroll.fleeBattle(); </font><font><i>// The troll shrieks in horror and runs away!</i></font><font> </font>
适用场景