本篇隨筆主要介紹用Java實現簡單的裝飾器設計模式:
先來看一下裝飾器設計模式的類別圖:
從圖中可以看到,我們可以裝飾Component介面的任何裝飾Component介面的任何裝飾Component介面的任何實作類,而這些實作類別也包括了裝飾器本身,裝飾器本身也可以再被裝飾。
下面是用Java實現的簡單的裝飾器設計模式,提供的是從基本的加入咖啡入手,可以繼續加入牛奶,巧克力,糖的裝飾器系統。
interface Component { void method(); } class Coffee implements Component { @Override public void method() { // TODO Auto-generated method stub System.out.println("倒入咖啡"); } } class Decorator implements Component { public Component comp; public Decorator(Component comp) { this.comp = comp; } @Override public void method() { // TODO Auto-generated method stub comp.method(); } } class ConcreteDecorateA extends Decorator { public Component comp; public ConcreteDecorateA(Component comp) { super(comp); this.comp = comp; } public void method1() { System.out.println("倒入牛奶"); } public void method2() { System.out.println("加入糖 "); } public void method() { super.method(); method1(); method2(); } } class ConcreteDecorateB extends Decorator { public Component comp; public ConcreteDecorateB(Component comp) { super(comp); this.comp = comp; } public void method1() { System.out.println("加入巧克力"); } public void method() { super.method(); method1(); } } public class TestDecoratePattern { public static void main(String[] args) { Component comp = new Coffee(); comp.method(); System.out.println("--------------------------------------------------"); Component comp1 = new ConcreteDecorateA(comp); comp1.method(); System.out.println("--------------------------------------------------"); Component comp2 = new ConcreteDecorateB(comp1); comp2.method(); System.out.println("--------------------------------------------------"); Component comp3 = new ConcreteDecorateB(new ConcreteDecorateA(new Coffee())); comp3.method(); System.out.println("--------------------------------------------------"); Component comp4 = new ConcreteDecorateA(new ConcreteDecorateB(new Coffee())); comp4.method(); } }
運行結果:
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持PHP中文網。
更多Java裝飾器設計模式初探相關文章請關注PHP中文網!