一、 定义
代理模式(Proxy),为其他对象提供一种代理以控制对这个对象的访问。
二、 结构图
三、 示例代码
//抽象类
package org.example.ProxyModel;
public class Subject {
public void request(){
System.out.println("abstract class");
}
}
//真实对象
package org.example.ProxyModel;
public class RealSubject extends Subject {
@Override
public void request() {
System.out.println("real request");
}
}
//代理对象
package org.example.ProxyModel;
public class Proxy extends Subject {
RealSubject realSubject = null;
@Override
public void request() {
if(realSubject == null)
realSubject = new RealSubject();
realSubject.request();
}
}
//测试类
package org.example.ProxyModel;
public class TestProxy {
public static void main(String[] args) {
Proxy pro = new Proxy();
pro.request();
}
}