大話設計模式--裝飾模式
阿新 • • 發佈:2018-11-16
裝飾模式:動態地給一個物件新增一些額外的職責,就增加功能來說,裝飾模式比生成子類更加靈活。
Component是定義了一個物件介面,可以給這些物件動態地新增職責,ConcreteComponent是定義了一個具體的物件,也可以給這些物件新增一些職責。Decorator,裝飾抽象類,繼承了Component,從外類來擴充套件Component類的功能,但對於Component來說,是無需知道Decorator的存在的,至於ConcreteDecorator就是具體的裝飾物件,起到給Component新增職責的功能。
public abstract class Component { public abstract void Operation(); }
public class ConcreteComponent extends Component {
@Override
public void Operation() {
}
}
public abstract class Decorator extends Component { protected Component component; public void setComponent(Component component) { this.component = component; } @Override public void Operation() { if (component != null) { component.Operation(); } } }
public class ConcreteDecoratorA extends Decorator {
private String addedState;
@Override
public void Operation() {
super.Operation();
addedState = "New State";
System.out.println("對具體物件A的操作");
}
}
public class ConcreteDecoratorB extends Decorator { @Override public void Operation() { super.Operation(); AddedBehavior(); System.out.println("具體裝飾物件B的操作"); } private void AddedBehavior() { } }
public class Main {
public static void main(String[] args) {
ConcreteComponent c = new ConcreteComponent();
ConcreteDecoratorA decoratorA = new ConcreteDecoratorA();
ConcreteDecoratorB decoratorB = new ConcreteDecoratorB();
decoratorA.setComponent(c);
decoratorB.setComponent(decoratorA);
decoratorB.Operation();
}
}