The English original of the proxy mode is: Provide a surrogate or placeholder for another object to control access to it. This means: Provide a proxy for other objects to control access to this object.
There are three types of roles:
1, abstract theme: is the real topic and the interface of the agent theme, the agent theme to implement this abstract theme, so you can use the proxy theme Proxy real topic.
2. Real topic: The specific performer of business logic, the object of being represented.
3, Agent theme: This role has a real theme of the reference, you can increase the operation before and after the actual theme.
Class diagram for Proxy mode:
The corresponding code for each class:
Abstract Topics:
Package com.zz.proxy;/** * Abstract subject * Copyright April 14, 2015 * created by TXXS * All right reserved */public interface Subject { Define a request for public void request ();
Real theme:
Package com.zz.proxy;/** * True Theme * Copyright April 14, 2015 * created by TXXS * All right reserved */public class Realsubject I Mplements Subject {public void request () {//Business logic Processing}}
Agent topic:
Package com.zz.proxy;/** * Agent subject * Copyright April 14, 2015 * created by TXXS * All right reserved */public class Proxysubject Implements Subject {private Subject subject;public proxysubject (Subject Subject) {this.subject = Subject;} Add methods based on the original method @overridepublic void request () {this.beforerequest (); Subject.request (); This.afterrequest ();} Action before request private void Beforerequest () {//Pre-}//request operation private void Afterrequest () {//Processing end}}
Advantages of the proxy mode:
1, clear responsibilities: Real role can only realize the actual business logic, do not implement non-business, through the agent to achieve the subsequent business add, is the programming logic clear.
2, High scalability: The real role is to achieve a common interface, the proxy object can proxy real role.
3. Flexible: The proxy class can determine the real role of the agent at run time.
Use an instance to apply Proxy mode ——— House rental. There are two ways a Gobargain () method is used to negotiate the price, and the other method is to rent the Houserental () method when the pricing is complete. The owner of the property has realized the interface of the house rental, there is a housing rental intermediary, the intermediary also realized the interface of housing rental. This intermediary can represent these houses. SOURCE download
Implementation results:
Design mode--proxy mode