Design Mode-proxy Mode
The original proxy mode is: Provide a surrogate or placeholder for another object to control access to it. it means to Provide a proxy for other objects to control access to this object.
There are three roles:
1. Abstract topic: it is the interface of the real subject and the proxy topic. To implement this abstract topic, you can use the proxy topic to represent the real topic.
2. Real theme: the specific performer of the business logic, the object to be proxy.
3. Proxy topic: this role has a reference to a real topic. You can add an operation before and after the actual topic operation.
Class Diagram of proxy mode:
Code corresponding to each class:
Abstract topic:
Package com. zz. proxy;/*** abstract Topic * 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;/*** real Subject * Copyright April 14, 2015 * created by txxs * all right reserved */public class RealSubject implements Subject {public void request () {// business logic processing }}
Proxy topic:
Package com. zz. proxy;/*** proxy 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 the method @ Overridepublic void request () {this. beforeRequest (); subject. request (); this. afterRequest ();} // the operation before the request is private void beforeRequest () {// preprocessing} // The operation after the request is private void afterRequest () {// processing ends }}
Advantages of proxy mode:
1. Clear responsibilities: a real role can only implement the actual business logic. It does not need to implement non-own business. It is clear to add subsequent business through proxy.
2. high scalability: if a real role implements a public interface, the proxy object can proxy the real role.
3. Flexibility: the proxy class can determine the real role of the proxy at runtime.
Use an instance to apply the proxy mode-house rental. If a user owns a house for rent, either the goBargain () method is used to negotiate the price, or the houseRental () method is used to rent a house after the price is completed. Users who own houses implement the house rental interface. There is a house rental agency, which also implements the house rental interface. This intermediary can act on behalf of these houses. Source code download
Effect: