This article describes the static proxy mode of Java design pattern. Share it for your reference, as follows:
In proxy mode, some other operations can be attached to the original basis through proxy. The static proxy mode is relatively simple and does not require dynamic proxying when the program is running.
Roles of static proxy mode:
① Abstract role: a common interface between real objects and proxy objects. What needs to be done in declaring real objects and proxy objects.
② Real role: implement abstract roles, define the business logic to be implemented by the real role, and be called by the proxy role.
③ Agent role: implements abstract roles, is the agent of real roles, implements abstract methods through the business logic methods of real roles, and can attach their own operations.
Here is a simple example code for waiting agents:
1. Abstract role : a common interface between real objects and proxy objects. What needs to be done in declaring real objects and proxy objects.
package com.tydic.proxy;/** * Common interface between real and proxy roles* @author Administrator * */public abstract class Subject { //What real and proxy objects need to do public abstract void request();}2. Real role : An abstract role needs to be implemented, which is an object to be proxyed.
package com.tydic.proxy;/** * Real role* @author Administrator * */public class RealSubject extends Subject { @Override public void request() { System.out.println("from real subject!"); }}3. Agent role : implements abstract roles and holds a reference to a real role.
package com.tydic.proxy;/** * proxy role* @author Administrator * */public class ProxySubject extends Subject { private RealSubject realSubject;//The real role is referenced internally by the proxy role @Override public void request() { this.preRequest();//The operation attached before the real object operation if(null == realSubject){ realSubject = new RealSubject(); } realSubject.request();//Things completed by the real role this.postRequest();//Operation attached after the real object operation} private void preRequest(){ System.out.println("pre request!"); } private void postRequest(){ System.out.println("post request!"); }}4. Write client code
package com.tydic.proxy;public class Client { public static void main(String[] args) { Subject subject = new ProxySubject(); subject.request(); }}For more Java-related content, readers who are interested in this site can view the topics: "Introduction and Advanced Tutorial on Java Object-Oriented Programming", "Tutorial on Java Data Structure and Algorithm", "Summary of Java Operation DOM Node Skills", "Summary of Java File and Directory Operation Skills" and "Summary of Java Cache Operation Skills"
I hope this article will be helpful to everyone's Java programming.