Please wait...

小波Note

四川 · 成都市14 ℃
English

Java Proxy

成都 (cheng du)8/26/2024, 6:15:26 PM1.13kEstimated reading time 3 minFavoriteCtrl + D / ⌘ + D
cover
IT FB(up 主)
Back-end development engineer

The Proxy pattern is a structural design pattern that lets you provide a substitute or placeholder for another object. A proxy controls access to the original object, allowing you to perform something either before or after the request gets through to the original object, e.g. check access permissions, log the requests, cache the request results, etc.

定义接口

java
        public interface Subject {
    void request();
}

    

创建真实对象

java
        public class RealSubject implements Subject {
    @Override
    public void request() {
        System.out.println("RealSubject: Handling request.");
    }
}

    

创建代理对象

java
        public class Proxy implements Subject {
    private RealSubject realSubject;

    @Override
    public void request() {
        if (realSubject == null) {
            realSubject = new RealSubject();
        }
        System.out.println("Proxy request");
        realSubject.request();
    }
}

    

使用代理对象

java
        public class ProxyPatternDemo {
    public static void main(String[] args) {
        Subject proxy = new Proxy();
        proxy.request();
    }
}