Java design mode-proxy Mode
Preface:
The previous article mentioned the rule mode. In a single-class diagram, it looks like the proxy mode mentioned in this article. Both require a public interface and some implementation classes. The proxy class (Packaging class) encapsulates an interface object and provides client calls. These are similar. However, we need to pay attention to the details, that is, the proxy class here also needs to inherit the public interface here. In the policy mode, the packaging class does not need to do this.
Overview:
The proxy mode defines a proxy object of the original object to help the original object communicate with business outside the system. That is to say, if we cannot directly or do not want to directly use the original object, we can use a proxy to create the original object for operations.
Mode Description: Example-topic access 1. Background
Now let's assume that we want to build a website. This website allows three types of users to access: normal registered members, webmaster administrators, and visitors.
At this time, different visitors have different permissions on the content of a webpage. For example, a common registered member can access, post, and reply to a topic. The webmaster administrator can access, post, comment, and delete a topic. Visitors can only access this webpage.
2. Class Diagram
Figure-1 proxy mode class diagram
Based on the requirements in the above example, we can draw a class diagram in figure-1. However, although the three implementation classes in the class diagram have all the methods in the implementation interface, these implementation methods are not suitable for all the visitor objects. For example, although Member has the remove Method, ordinary Members cannot really delete a topic. Therefore, this control is necessary.
3. Code and Description: 1. Public interface
In a public interface, you need to define the basic behavior of some visitors. They are access topics, post topics, comment topics, and delete topics.
public interface Visitor { public void visit() throws RoleExcption; public void publish() throws RoleExcption; public void comment() throws RoleExcption; public void remove() throws RoleExcption;}
2. Specific implementation class
In this example, the specific implementation class does not have much content, but only overrides the methods in the implementation interface.
Public class Manager implements Visitor {@ Override public void visit () {System. out. println ("I am the website administrator and I have accessed this topic") ;}@ Override public void publish () {System. out. println ("I am the website administrator and I posted a topic") ;}@ Override public void comment () {System. out. println ("I am the website administrator and I commented on a topic") ;}@ Override public void remove () {System. out. println ("I am the website administrator, I deleted a topic ");}}
3. Proxy
The role of the proxy class is more important and necessary. They are responsible for controlling the behavior of a visitor on the topic to prevent unauthorized behavior. For example, a visitor cannot post or comment on a topic. You can use the method in the proxy for control. As follows:
Public class ProxyVisitor implements Visitor {private Visitor visitor = null; public ProxyVisitor () {// by default, visitor Visitor = new Tourist ();} public ProxyVisitor (visitor _ Visitor) {visitor = _ visitor;} @ Override public void visit () throws RoleExcption {visitor. visit () ;}@ Override public void publish () throws RoleExcption {if (visitor instanceof Tourist) {throw new RoleExcption ("visitors cannot post topics. Please register an account first ");} Visitor. publish () ;}@ Override public void comment () throws RoleExcption {if (visitor instanceof Tourist) {throw new RoleExcption ("visitors cannot post comments. Please register an account first ");} visitor. comment () ;}@ Override public void remove () throws RoleExcption {if (! (Visitor instanceof Manager) {throw new RoleExcption ("Only Administrators can delete topics") ;}visitor. remove ();}}
4. Client
Here we use different visitors to perform different operations and observe the results.
public class VisitorClient { public static void main(String[] args) { Manager manager = new Manager(); Member member = new Member(); Tourist tourist = new Tourist(); ProxyVisitor visitor = null; System.out.println("------------------- 1 --------------------"); try { visitor = new ProxyVisitor(manager); visitor.visit(); visitor.publish(); visitor.comment(); visitor.remove(); } catch (RoleExcption e) { System.err.println(e); } ThreadUtils.sleep(50); System.out.println("------------------- 2 --------------------"); try { visitor = new ProxyVisitor(member); visitor.visit(); visitor.publish(); visitor.comment(); visitor.remove(); } catch (RoleExcption e) { System.err.println(e); } ThreadUtils.sleep(50); System.out.println("------------------- 3 --------------------"); try { visitor = new ProxyVisitor(tourist); visitor.visit(); visitor.publish(); visitor.comment(); visitor.remove(); } catch (RoleExcption e) { System.err.println(e); } }}
5. Test Result diagram-2 Website access proxy test result
Example-student exam 1. Background
We have all gone through the student age, and we have all been tested. Of course, we have also done some harm (what? Have you ever cheated? When I didn't say ...).
A student's exam is a public action, but a student's cheating cannot be made public. Therefore, our examination method is public, while cheating is private. However, if our client program requires us to take advantage of the test. What should I do? You may say, this is easy to handle and reflect. This is indeed the case. reflection is required. However, this reflection is encapsulated in the proxy class, and then the method is made public from the proxy class. It is also shown in the following class diagram.
2. Class Diagram
This class diagram is similar to the class diagram of the above topic visitor. But there is another difference. I found it? That is, the Implementation class has an extra method cheat (cheating) than the interface class, and is a private method, but in the proxy class, this method is made public.
Figure-3 proxy mode class diagram
3. Code and description 1. Public interface
Same as above
public interface Student { public void examinate(); public void announce(); }
2. Specific implementation class
Same as above
Public class SeniorStudent implements Student {private String name = ""; private int score = 0; public SeniorStudent (String _ name) {name = _ name;} @ Override public void examinate () {score = NumberUtils. randomInteger (40,150);} @ SuppressWarnings ("unused") private void cheat () {System. out. println (name + "cheating... hush... "); score + = (NumberUtils. randomInteger (150-score);} @ Override public void announce () {System. out. println (name + "scored" + score + "score ");}}
3. Proxy
Note that the cheat method here is a public method. In this method, Java reflection is used to access private methods of specific implementation classes.
public class StudentProxy implements Student { private Student student = null; public StudentProxy(Student _student) { student = _student; } @Override public void examinate() { student.examinate(); } @Override public void announce() { student.announce(); } public void cheat() throws ClassNotFoundException, NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { Class clazz = Class.forName(student.getClass().getName()); Method method = clazz.getDeclaredMethod("cheat"); method.setAccessible(true); method.invoke(student); }}
4. Client
Same as above
Public class StudentProxyClient {public static void main (String [] args) {StudentProxy proxy = new StudentProxy (new Pupil ("James"); proxy. examinate (); proxy. announce (); try {proxy. cheat ();} catch (ClassNotFoundException | NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {e. printStackTrace ();} proxy. announce ();}}
5. Test Results
Figure-4 student examination proxy test results
Download GitHub source code:
Https://github.com/William-Hai/DesignPattern-Proxy