本篇随笔主要介绍用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(); } } |
运行结果:
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。