代理模式:通过代理调用真正的接口
public class App {
public static void main(String[] args) {
WizardTowerProxy proxy=new WizardTowerProxy(new IvoryTower());
proxy.enter(new Wizard("bob"));
proxy.enter(new Wizard("bob1"));
proxy.enter(new Wizard("bob2"));
proxy.enter(new Wizard("bob3"));
proxy.enter(new Wizard("bob4"));
}
}
public class IvoryTower implements WizardTower {
@Override
public void enter(Wizard wizard) {
System.out.println(wizard+"进入到塔内");
}
}
public class Wizard {
private final String name;
public Wizard(String name){
this.name=name;
}
@Override
public String toString() {
return name;
}
}
public interface WizardTower {
void enter(Wizard wizard);
}
public class WizardTowerProxy implements WizardTower{
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 {
System.out.println( wizard+" not allowed ");
}
}
}
核心思想:一个代理类实现这个接口,使用者调用这个代理的接口,这个代理接口可以接受继承那个接口的类