装饰者模式(DecoratorPattern)

场景

原装M4A1、AK47,添加消音器,瞄准镜。

实现

产品类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public interface Rifle {
/**
* 基本描述
*/
void describe();
}

public class M4A1 implements Rifle {
@Override
public void describe() {
System.out.println("出厂原装M4A1!!!");
}
}

public class AK47 implements Rifle {
@Override
public void describe() {
System.out.println("出厂原装AK47!!!");
}
}

装饰类

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
public abstract class RifleDecorator implements Rifle {
protected Rifle decoratedRifle;

public RifleDecorator(Rifle decoratedRifle) {
this.decoratedRifle = decoratedRifle;
}

@Override
public void describe() {
decoratedRifle.describe();
}
}

public class SilencerDecorator extends RifleDecorator {

public SilencerDecorator(Rifle decoratedRifle) {
super(decoratedRifle);
}

@Override
public void describe() {
super.describe();
System.out.println("添加消音器!!!");
}
}

public class GunsightDecorator extends RifleDecorator {

public GunsightDecorator(Rifle decoratedRifle) {
super(decoratedRifle);
}

@Override
public void describe() {
super.describe();
System.out.println("添加瞄准镜!!!");
}
}

测试

1
2
3
4
5
6
7
8
9
10
11
12
13
public class Test {
public static void main(String[] args) {
Rifle m4A1 = new M4A1();
m4A1 = new SilencerDecorator(m4A1);
m4A1 = new GunsightDecorator(m4A1);
m4A1.describe();
System.out.println("********************");
Rifle ak47 = new AK47();
ak47 = new SilencerDecorator(ak47);
ak47 = new GunsightDecorator(ak47);
ak47.describe();
}
}

出厂原装M4A1!!!
添加消音器!!!
添加瞄准镜!!!


出厂原装AK47!!!
添加消音器!!!
添加瞄准镜!!!

个人理解

这个装饰者模式就相当于并没有改变原来的对象结构,但是给原来对象穿上了一件衣服。就是创建一些修饰的类,用来包装原来的类。就像游戏中一个人初始化的时候没有任何装备,然后用武器来修饰,各种装备来修饰这个初始化的人。