Java Design Pattern learning, java Design Pattern
Proxy)
In fact, the name of each mode indicates the role of this mode. The proxy mode is to add one more proxy class to perform some operations for the original object. For example, we go back to the intermediary when renting a house. Why? Because you do not have comprehensive information about the houses in the region, I hope you can find someone you are more familiar with to help you. This is what proxy means here. If we go to court sometimes, we need to ask a lawyer. Because he has expertise in law, he can operate for us and express his thoughts. Let's take a look at the relationship diagram:
As described above, the proxy mode is easy to understand. Let's look at the Code:
public interface Sourceable { public void method(); } public class Source implements Sourceable { @Override public void method() { System.out.println("the original method!"); } } 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:
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 of proxy mode:
If the existing method needs to be improved when used, there are two methods:
1. modify the original method to adapt. This violates the principle of "opening to extensions and disabling modifications.
2. A proxy class is used to call the original method and control the results. This method is the proxy mode.
With the proxy mode, you can clearly divide functions and facilitate later maintenance!
Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.