设计模式-代理模式

代理模式 (Proxy)

参考: https://github.com/iluwatar/java-design-patterns

故事描述

巫师需要进入象牙塔才能保卫家园,象牙塔只能容纳3位巫师,这里使用代理模式来控制巫师进入象牙塔

个人理解

代理,客户端访问的是真实对象的包装或代理对象,由代理对象简单的访问真实对象,或者添加额外的逻辑. Spring 的事务控制使用的就是代理模式.

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
75

/**
*
* Wizard
*
*/
public class Wizard {

private final String name;

public Wizard(String name) {
this.name = name;
}

@Override
public String toString() {
return name;
}

}

/**
* WizardTower interface
*/
public interface WizardTower {

void enter(Wizard wizard);
}

/**
*
* 需要代理的对象
*
*/
public class IvoryTower implements WizardTower {

private static final Logger LOGGER = LoggerFactory.getLogger(IvoryTower.class);

public void enter(Wizard wizard) {
LOGGER.info("{} enters the tower.", wizard);
}

}


/**
*
* The proxy controlling access to the {@link IvoryTower}.
*
*/
public class WizardTowerProxy implements WizardTower {

private static final Logger LOGGER = LoggerFactory.getLogger(WizardTowerProxy.class);

private static final int NUM_WIZARDS_ALLOWED = 3;

private int numWizards;

private final WizardTower tower;

public WizardTowerProxy(WizardTower tower) {
this.tower = tower;
}

@Override
public void enter(Wizard wizard) {
// 控制进入塔内巫师的数量
if (numWizards < NUM_WIZARDS_ALLOWED) {
tower.enter(wizard);
numWizards++;
} else {
LOGGER.info("{} is not allowed to enter!", wizard);
}
}
}