Design Mode 3 static proxy mode, Design Mode Static proxy
I. Overview 1. What is the proxy mode?
To hide and protect the target object, a proxy is provided for other objects to control access to the target object.
2. What is static proxy mode?
There are two proxy modes:
- Static Proxy: the proxy object is fixed.
- Dynamic Proxy: the proxy object is not fixed.
Static proxy Mode 1. Basic Structure:
Parent class: it can be an interface, abstract class, and general class. It is generally an interface and ensures that the proxy object can be operated as the target object.
Target class: implements the parent class.
Proxy class: not only has the same parent class as the target, but also contains the target class object.
2. Implement the proxy class containing the target object
The proxy mode is used to hide and protect the target object. Therefore, the target object cannot be created by the user, but is created inside the proxy class. It is created in the proxy class constructor method to hide the target object.
3. Implement the Demo Interface
package com.designmode.proxy.staticTest.demo02;public interface ISomeService { String doSome(String message);}
Target class
package com.designmode.proxy.staticTest.demo02;public class SomeServiceImpl implements ISomeService { @Override public String doSome(String message) { // TODO Auto-generated method stub return message; }}
Proxy
Package com. designmode. proxy. staticTest. demo02; public class SomeServiceProxy implements ISomeService {private ISomeService service; public SomeServiceProxy () {super (); service = new SomeServiceImpl (); // create the target object inside the proxy constructor} @ Override public String doSome (String message) {return service. doSome (message ). toUpperCase ();}}
Test class
package com.designmode.proxy.staticTest.demo02;import org.junit.Test;public class StaticProxyTest { @Test public void test01() { ISomeService proxy = new SomeServiceProxy(); String result = proxy.doSome("abc"); System.out.println("result=" + result); }}