代理模式

代理设计模式UML类图

代理设计模式UML类图

代理设计模式java代码实现

/**
* WizardTower interface.
精灵塔
*/
public interface WizardTower {

void enter(Wizard wizard);
}

/**
* Wizard.
巫师
*/
public class Wizard {

private final String name;

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

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

}

/**
* The object to be proxyed.
IvoryTower象牙塔
*/
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);
}
}
}

/**
* A proxy, in its most general form, is a class functioning as an interface to something else. The
* proxy could interface to anything: a network connection, a large object in memory, a file, or
* some other resource that is expensive or impossible to duplicate. In short, a proxy is a wrapper
* or agent object that is being called by the client to access the real serving object behind the
* scenes.
在最一般的形式上,代理是一个类,充当与其他对象的接口。 代理可以与任何接口:网络连接,内存中的大对象,文件或其他昂贵或无法复制的其他资源。 简而言之,代理是客户端调用的包装器或代理对象,以访问幕后的真实服务对象。
*
* <p>The Proxy design pattern allows you to provide an interface to other objects by creating a
* wrapper class as the proxy. The wrapper class, which is the proxy, can add additional
* functionality to the object of interest without changing the object's code.
*<p>通过代理设计模式,您可以通过创建包装器类作为代理来为其他对象提供接口。 包装类(它是代理)可以在不更改对象代码的情况下向目标对象添加其他功能。
* <p>In this example the proxy ({@link WizardTowerProxy}) controls access to the actual object (
* {@link IvoryTower}).
<p>在此示例中,代理({@link WizardTowerProxy})控制对实际对象({@link IvoryTower})的访问。
*/
public class App {

/**
* Program entry point.
*/
public static void main(String[] args) {

var 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"));

}
}

应用场景

spring动态代理生成对象

spring动态代理生成对象

Mybatis中Mapper动态代理机制

dubbo动态代理模式生成proxy过程

dubbo动态代理模式生成proxy过程