【设计模式无难事】——代理
一、意图
为其他对象提供一种代理以控制对这个对象的访问。
二、例子
需求场景
法师进入魔法塔
分析&实作
代理模式实现
1,魔法塔接口
WizardTower.java
/**
* WizardTower interface
*/
public interface WizardTower {
void enter(Wizard wizard);
}
2,实现接口
IvoryTower.java
/**
*
* The object to be proxyed.
*
*/
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);
}
}
3,定义一个法师类
Wizard.java
/**
*
* Wizard
*
*/
public class Wizard {
private final String name;
public Wizard(String name) {
this.name = name;
}
@Override
public String toString() {
return name;
}
}
4,做一个魔法塔代理类
WizardTowerProxy.java
/**
*
* 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);
}
}
}
5,运行
public static void main(String[] args) {
WizardTowerProxy proxy = new WizardTowerProxy(new IvoryTower());
proxy.enter(new Wizard("Red wizard"));
proxy.enter(new Wizard("White wizard"));
proxy.enter(new Wizard("Black wizard"));
proxy.enter(new Wizard("Green wizard"));
proxy.enter(new Wizard("Brown wizard"));
}
}
6,输出
16:46:42.993 [main] INFO com.iluwatar.proxy.IvoryTower - Red wizard enters the tower.
16:46:42.998 [main] INFO com.iluwatar.proxy.IvoryTower - White wizard enters the tower.
16:46:42.998 [main] INFO com.iluwatar.proxy.IvoryTower - Black wizard enters the tower.
16:46:42.998 [main] INFO com.iluwatar.proxy.WizardTowerProxy - Green wizard is not allowed to enter!
16:46:42.998 [main] INFO com.iluwatar.proxy.WizardTowerProxy - Brown wizard is not allowed to enter!
三、思考
1,代理类在使用者和真实服务对象之间增加了一个“层”,通过非侵入式改造对象,为真实服务对象增加更多的控制功能。
2,代理侧重点在控制访问。
Tips:一个类,它提供了对一个接口的访问控制,是代理模式的特征
四、代理模式在android源码中的例子
附:
本文源代码在这里
有任何问题,欢迎留言或Email我 zzy_2002@126.com
转载请注明出处:http://blog.csdn.net/zzy_801011/article/details/79035321
谢谢