Java裝潢器設計形式初探。本站提示廣大學習愛好者:(Java裝潢器設計形式初探)文章只能為提供參考,不一定能成為您想要的結果。以下是Java裝潢器設計形式初探正文
本篇漫筆重要引見用Java完成簡略的裝潢器設計形式:
先來看一下裝潢器設計形式的類圖:
從圖中可以看到,我們可以裝潢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(); } }
運轉成果:
以上就是本文的全體內容,願望對年夜家的進修有所贊助,也願望年夜家多多支撐。