In fact, each pattern name indicates the role of the mode, proxy mode is more than one proxy class out, for the original object to do some operations, such as we rent the house when back to find intermediary, why? Because you do not have comprehensive information about the housing in the area, I hope to find a more familiar person to help you do, the agent here is the meaning. If we have a lawsuit, we need a lawyer, because the lawyer has expertise in law and can act on our behalf and express our ideas. Take a look at the diagram first:
According to the above explanation, the proxy mode is easier to understand, we look at the code:
[Java]View Plaincopy
- Public interface Sourceable {
- public void Method ();
- }
[Java]View Plaincopy
- public class Source implements sourceable {
- @Override
- public void Method () {
- System.out.println ("The original method!");
- }
- }
[Java]View Plaincopy
- public class Proxy implements sourceable {
- private source source;
- Public Proxy () {
- Super ();
- This.source = new Source ();
- }
- @Override
- public void Method () {
- Before ();
- Source.method ();
- Atfer ();
- }
- private void Atfer () {
- System.out.println ("after proxy!");
- }
- private void before () {
- System.out.println ("before proxy!");
- }
- }
Test class:
[Java]View Plaincopy
- public class Proxytest {
- public static void Main (string[] args) {
- sourceable Source = new Proxy ();
- Source.method ();
- }
- }
Output:
Before proxy!
The original method!
After proxy!
Application Scenarios for Proxy mode:
If existing methods need to be improved when used, there are two ways to do this:
1, modify the original method to adapt. This violates the principle of "open for expansion, closed for modification".
2, is to use a proxy class to call the original method, and the resulting results are controlled. This approach is proxy mode.
Using the proxy mode, you can divide the function more clearly and help to maintain later!
The eight-agent mode of Java design mode (proxy)