本篇隨筆主要介紹用Java實現簡單的裝飾器設計模式:
先來看一下裝飾器設計模式的類圖:
從圖中可以看到,我們可以裝飾Component接口的任何實現類,而這些實現類也包括了裝飾器本身,裝飾器本身也可以再被裝飾。
下面是用Java實現的簡單的裝飾器設計模式,提供的是從基本的加入咖啡入手,可以繼續加入牛奶,巧克力,糖的裝飾器系統。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
|
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(); } } |
運行結果:
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。