Java design mode--proxy mode

Source: Internet
Author: User
Tags class manager

Preface:

The previous article talked about the strategy model. On the single-class diagram, it is somewhat like the proxy model that this article is going to say. Requires a common interface and some implementation classes. The proxy class (wrapper class) encapsulates an interface object that provides a client call. These are very similar. However, there is one detail that needs to be noted that the proxy class here also needs to inherit the public interface here. In the policy mode, the wrapper class does not need to do so.

Overview:

A proxy pattern is a proxy object that defines an original object to facilitate communication between the original object and the business outside the system. That is, if we do not directly or do not want to use the original object directly, then we can use to create a proxy for the original object to operate.

This article link:http://blog.csdn.net/lemon_tree12138/article/details/50326817--Coding-naga
-- reprint please indicate the source


Mode Description:Example--topic interview1. Background

Now let's assume we're going to build a website. This site allows access to three categories of users, namely: ordinary registered Members, webmaster administrators, tourists.

At this time, different visitors have different permissions on the content of a particular page. For example, a regular registered member can access, post, and comment (reply) a topic; a webmaster can access, post, comment, and delete a topic, while visitors can only access this page.

2. Class Diagram


Figure-1 Proxy pattern 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 a class diagram have all the methods implemented in the interface, these implementations are not suitable for all visitor objects. For example, although the member has the Remove method, but ordinary members can not really delete a topic. So this control is very necessary.

3. Code and Description:1. Public interface

The basic behavior of some visitors needs to be defined in the public interface. Access to topics, topics, comment topics, and delete topics, respectively.

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 case, the implementation of the class is not much content, just rewrite the implementation of the method in the interface.

public class Manager implements Visitor {    @Override public    Void visit () {        System.out.println ("I am the administrator of the site, I visited this topic ");    }    @Override public    Void Publish () {        System.out.println ("I am the administrator of the site, I published a topic")    ;    @Override public    void Comment () {        System.out.println ("I am the administrator of the site, I commented on a topic");    }    @Override public    Void Remove () {        System.out.println ("I am the administrator of the site, I deleted a theme");}    }

3. Proxy class

The role of the proxy class is still more important, and necessary. They are responsible for controlling the behavior of a visitor to the topic and preventing unauthorized behavior. For example, a visitor cannot publish or comment on a topic. Then it can be implemented by means of the proxy method. As follows:

public class Proxyvisitor implements Visitor {private Visitor Visitor = null;    Public Proxyvisitor () {//The default is 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 NE        W roleexcption ("Visitors cannot publish the subject, please register the account First");    } visitor.publish (); } @Override public void comment () throws roleexcption {if (visitor instanceof tourist) {throw NE        W roleexcption ("Visitors cannot comment, please register account first");    } visitor.comment (); } @Override public void Remove () throws Roleexcption {if (!) (        Visitor instanceof Manager) {throw new Roleexcption ("Only administrators can delete themes");    } 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 resultsFigure-2 Site Access Proxy test results

Example--Student exams1. Background

We have all experienced the students ' time, have also tested, of course, have done the harm (what?) You haven't done any harm? Well, when I didn't say ... )。

Student exams are an open act, and students cheat but not openly. So, our test method is public, but cheating is private. However, if our client program needs us to do some cheating in the exam. What do we do? You might say, this is good, reflex ah. Indeed, it is the use of reflection. But this reflection we encapsulated in the proxy class, and then from the proxy class to make this method into a public method. This is also reflected in the following class diagram.

2. Class Diagram

This class diagram is similar to the class diagram of the above topic visitors. But there is a different place, found not? That is, there is a method in the implementation class that is more than the interface class cheat (cheat), and is a private method, but in the proxy class, this method is made public.


Figure-3 Proxy pattern class diagram

3. Code and Description1. Public interface

Note Ibid.

Public interface Student {public    void examinate ();        public void announce ();    }

2. Specific implementation class

Note Ibid.

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 (+);    }    @SuppressWarnings ("unused")    private void Cheat () {        System.out.println (name + "is cheating ...) Hush ... ");        Score + = (Numberutils.randominteger (150-score));    }    @Override public    Void announce () {        System.out.println (name + "TEST" + score + "Min");}    }

3. Proxy class

Note that the cheat method here is an open method. In this method, a Java reflection is used to access the private method of implementing the class.

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 = Clazz.getdeclaredmethod ("cheat");        Method.setaccessible (true);        Method.invoke (student);    }}

4. Client

Note Ibid.

public class Studentproxyclient {public    static void Main (string[] args) {        Studentproxy proxy = new Studentproxy (n EW pupil ("xiaoming"));        Proxy.examinate ();        Proxy.announce ();        try {            proxy.cheat ();        } catch (ClassNotFoundException | Nosuchmethodexception                | SecurityException | Illegalaccessexception                | IllegalArgumentException | InvocationTargetException e) {            e.printstacktrace ();        }        Proxy.announce ();    }}

5. Test results


Figure-4 test results for student exam agents

GitHub source Download:

Https://github.com/William-Hai/DesignPattern-Proxy

Java design mode--proxy mode

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.