Java設計模式之20 —— 裝飾模式(1)
裝飾模式是一種結構型設計模式。其使用一種對客戶端透明的方式,來動態的擴充套件物件的功能。同時,它也是繼承關係的一種替代方案之一。定義:動態地給一個物件新增一些額外的職責。就增加個來說,裝飾模式比生成子類更為靈活。
所以,我們可以在需要透明而且動態地擴充套件類的功能時,所以裝飾模式。
1 建立一個被裝飾的原始物件,也可以是介面還在抽象類:
package decoratorpattern;
public abstract class Component { public abstract void operate();
}
2 建立原始物件的具體實現類:
package decoratorpattern;
public class ConcretComponent extends Component{
@Override public void operate() { System.out.println("ConcretComponent------operate"); } }
3 建立一個抽象裝飾者:
package decoratorpattern;
public class Decorator extends Component{ private Component component; public Decorator(Component component) { super(); this.component = component; } @Override public void operate() { component.operate(); } }
4 建立裝飾著的具體實現類,做具體的實現;
package decoratorpattern;
public class ConcretDecoratorA extends Decorator{
public ConcretDecoratorA(Component component) { super(component); } @Override public void operate() { super.operate(); operateA(); } public void operateA(){ System.out.println("ConcretDecoratorA--------operateA"); } public void operateB(){ System.out.println("ConcretDecoratorA--------operateB"); } }
以及
package decoratorpattern;
public class ConcretDecoratorB extends Decorator{
public ConcretDecoratorB(Component component) { super(component); } @Override public void operate() { super.operate(); operateB(); } public void operateA(){ System.out.println("ConcretDecoratorB--------operateA"); } public void operateB(){ System.out.println("ConcretDecoratorB--------operateA"); } }
5 測試執行的效果:
package decoratorpattern;
public class Client { public static void main(String[] args) { Component component = new ConcretComponent(); Decorator decoratorA = new ConcretDecoratorA(component); decoratorA.operate(); Decorator decoratorB = new ConcretDecoratorB(component); decoratorB.operate(); } }