Structural Patterns Part 4/7: Decorator Pattern
目录
Definition
Decorator Pattern是对一个已有对象的再封装,可以说实现了一个Wrapper的功能。它会在已有对象的基础上添加更多的功能而不会改变已有对象的结构(通过组合来实现),通常Decorator和其封装的对象是来自同一个类或接口的。
一个现实中的例子就是JavaEE中的DAO实体,对应的是数据库中的表记录,一般设计好了就不会再改变,所以很多情况下都会对这个实体进行再封装。
何时使用?当希望在现有对象的基础上添加新的功能而又不想改变其结构时。
使用频率: Medium
UML Class Diagram
Implementation
现在有个Pad,它本身可以玩游戏,现在对它进行装饰一下,从而可以通过键鼠或者是手柄来玩它上面的游戏。
// Pad.java
package designpatternsstructuralpatterns.decorator;
public interface Pad {
void playGames();
}
// PadImpl.java
package designpatternsstructuralpatterns.decorator;
class iPad implements Pad {
@Override
public void playGames() {
System.out.println("Playing Games on an iPad.");
}
}
// DecoratorDemo.java
package designpatternsstructuralpatterns.decorator;
public class DecoratorDemo {
public static void main(String[] args) {
Pad iPad = new iPad();
Decorator kmDecorator = new KeyboardMouseDecorator(iPad);
kmDecorator.playGames();
System.out.println("=========================");
Decorator jsDecorator = new JoyStickDecorator(kmDecorator);
jsDecorator.playGames();
}
}
abstract class Decorator implements Pad {
protected Pad decoratedPad;
public Decorator(Pad decoratedPad) {
this.decoratedPad = decoratedPad;
}
public abstract void playGames();
protected abstract void playWithOuterDevice();
}
class KeyboardMouseDecorator extends Decorator {
public KeyboardMouseDecorator(Pad decoratedPad) {
super(decoratedPad);
}
@Override
public void playGames() {
decoratedPad.playGames();
playWithOuterDevice();
}
@Override
protected void playWithOuterDevice() {
System.out.println("With a keyboard and a mouse!!!");
}
}
class JoyStickDecorator extends Decorator {
public JoyStickDecorator(Pad decoratedPad) {
super(decoratedPad);
}
@Override
public void playGames() {
decoratedPad.playGames();
playWithOuterDevice();
}
@Override
protected void playWithOuterDevice() {
System.out.println("With a joy stick!!!");
}
}
// output
Playing Games on an iPad.
With a keyboard and a mouse!!!
=========================
Playing Games on an iPad.
With a keyboard and a mouse!!!
With a joy stick!!!