Table of contents
Proxy mode (Proxy)
Provides a proxy for other objects to control access to this object. The Proxy mode is suitable when a more general and complex object pointer is needed instead of a simple pointer.
Applicable scene
- Remote Proxy provides local representation of an object in different address spaces.
- Virtual Proxy creates expensive objects as needed.
- Protection Proxy controls access to the original object and is used when the object should have different access rights.
- A Smart Reference replaces a simple pointer and performs some additional operations when accessing an object. Typical uses include: Counting references to an actual object so that it can be automatically released when no reference is made: Loading a persistent object into memory when it is referenced for the first time: Checking whether an actual object is accessed before accessing it It has been locked to ensure that other objects cannot change it.
✦ Proxy saves a reference so that the proxy can access the entity; provides an interface that is the same as the Subject's interface so that the proxy can be used instead of the entity: controls access to the entity and may be responsible for creating and deleting it; other functions depend on the proxy Type: Remote Proxy is responsible for encoding the request and its parameters and sending the encoded request to the entity in a different address space; Virtual Proxy can cache additional information of the entity to delay access to it; Protection Proxy checks whether the caller has Access rights necessary to fulfill a request.
✦ Subject defines the common interface between RealSubject and Proxy, so that Proxy can be used wherever RealSubject is used.
✦ RealSubject defines the entity represented by Proxy.
Proxy pattern example code (Java)
interface Subject {
public void buy();
}
class Proxy implements Subject {
protected RealSubject realSubject;
public Proxy(RealSubject realSubject) {
this.realSubject = realSubject;
}
@Override
public void buy() {
System.out.println("办理购买前的手续");
realSubject.buy(); // 付钱
System.out.println("办理购买后的手续");
}
}
class RealSubject implements Subject {
@Override
public void buy() {
System.out.println("付钱");
}
}
public class ProxyPattern {
public static void main(String[] args) {
RealSubject realSubject = new RealSubject();
Proxy proxy = new Proxy(realSubject);
proxy.buy();
}
}
For details on other design patterns, please refer to other blog posts in this column.
Special thanks to zst_2001 for his help during the preparation for the soft exam. Posted in the personal space of blogger B station
zst_2001