Proxy Mode with Android

Source: Internet
Author: User

Agent mode (proxy)


First, What is proxy mode

Let's take a look at the official argument, the proxy pattern is to provide a proxy for other objects to control access to the object.

It seems that the official statement is a bit official, to see or let people feel not at a loss, or do not understand what is the proxy model, what is used to do something.

In fact, the term agent is not unfamiliar to us, there are many examples of agents in life. For example, campus agents, on behalf of the campus, the campus agent is for his corresponding boss of the agent, and this campus agency work is to visit students on campus, such as the students to carry out questionnaires and so on. In this case, the student is the other object of the official story, and the supervisor of the campus agent controls the student's visit by controlling the campus agent. This should be understood a little bit.


Second, class diagram for proxy mode


Third, implementation code for the proxy pattern (c + + implementation)

With the above-mentioned campus agent as an example, we come to see the style of proxy mode, in order to better understand this model, or to make a little explanation. In the following code, there will be three classes, Worker, Boss, and Schoolproxy, each corresponding to three classes of subject, realsubject, and proxies, and the Dosurvey method in these classes is equivalent to the request method in.

Note: In fact, is just a proxy model UML model diagram, request actually represents all proxies and realsubject of the common interface, and not just one written here.

The implementation code is as follows (Proxy.cpp):

1, the worker class is defined as follows, it has a Dosurvey interface

Class Worker{public:     virtual void Dosurvey () = 0;     Virtual ~worker () {}};

2, the Boss class is defined as follows, it inherits the worker class, and implements the Dosurvey interface

Class Boss:public Worker{public:     virtual void Dosurvey ()     {        cout << "The ABCDE Company does sruvey!" < ;< Endl;     }};

3, the Schoolproxy class is defined as follows, it also inherits the worker class, and implements the Dosurvey interface, which maintains a reference to the object of a boss class and calls the Boss Dosurvey method in its Dosurvey method.

Class Schoolproxy:public Worker{public:     schoolproxy ():        _boss (NULL)     {     }     virtual ~schoolproxy ()     {        if (_boss! = NULL)        {            delete _boss;        }     }     Schoolproxy (const schoolproxy&proxy)     {        _boss = Newboss (*proxy._boss);     }     schoolproxy& operator= (const schoolproxy &RHS)     {        if (this! = &RHS)        {            Schoolproxytmp_ Proxy (RHS);            Boss *tmp_boss =tmp_proxy._boss;            Tmp_proxy._boss = _boss;            _boss = Tmp_boss;        }        return *this;     }     virtual void Dosurvey ()     {        if (_boss = = NULL)        {            _boss = new boss ();        }        _boss->dosurvey ();     } Private:     Boss *_boss;};

Note: Bosses in this class can also use objects without using pointers. But because languages such as Java or C # do not support objects on the stack, all objects are new, so this is more like Java and C #.

4. Call method as follows:

int main () {Schoolproxy *proxy = new Schoolproxy ();p Roxy->dosurvey ();d elete Proxy;return 0;}
from the code above, we can clearly see how the campus agent Schoolproxy is helping its boss to complete the work of the investigation.

Four, Application of proxy mode

Look at the above code, I think the operation and principle of proxy mode, we are almost understandable, but in fact, there are more than one agent, according to the usual use, can be divided into four categories.

1) Remote Agent

It provides a local representation of an object in a different address space. This allows you to hide the fact that an object exists in a different address space, which is an example of webserver.

2) Virtual Agent

It creates more expensive objects based on requirements, and it holds the real objects that take a long time to instantiate. For example, when we browse the Web page, there may be some relatively large pictures, although the picture is larger, but you can open the page quickly, but the picture is not displayed in the first time, it may be a few seconds before the normal display, here is the virtual agent to replace the real picture.

3) Protection agent

It is used to control access to the original object, and the protection agent is used when the object should have different access rights.

4) Smart Reference

It is used to mean that when a real object is called, the agent performs additional actions to handle something else. For example, a smart pointer in C + +, which replaces a simple pointer, performs some extra work on the object it points to.

Five, the share_ptr of real application of proxy mode

Look at the above code, read the above explanation, you may feel that the proxy mode does not work, then you are wrong, below to see, the above four kinds of proxy mode one of the powerful use of smart references.

A programmer who has used C + + must know that smart pointers are a good thing, and it can make it much less difficult for us to manage memory, because it makes the pointer to the heap memory like stack memory, which can be automatically freed by the way the object manages resources.

The following is the implementation of the share_ptr to illustrate the application of intelligent reference Proxy mode, first to see the definition of the class:

template <        TypeName T>class shareptr{public:shareptr (T *tptr = NULL);        Shareptr (const shareptr &sptr);        shareptr& operator= (const shareptr &sptr);        shareptr& operator= (T *tptr);        ~shareptr ();        t&operator* () const;        T*operator-> () const;        BOOL operator== (const SHAREPTR &sptr) const;        BOOL Operator!= (const SHAREPTR &sptr) const;        BOOL operator== (const T *tptr) const;        BOOL Operator!= (const T *tptr) const;   Const t* GETPTR () const;        private://function void _decused ();        inline void _nulltest () const;        inline bool _issame (const SHAREPTR &sptr) const;   inline bool _issame (const T *tptr) const;        Private://data T *_ptr; size_t *_used;//reference count, releases the object that PTR points to 0 o'clock; 

It's only so much defined, and by looking at the definition above, you can ask questions, does this really apply the above-mentioned proxy mode? The above proxy mode is not to have a subject class, a Realsubject class, and a proxy class? While the Realsubject class and proxy are subclasses of subject, do you need to define subject interfaces? Why is there only one class here?

Now you don't see it, I don't blame you. Look down and you'll understand.

Smart pointers, for example, in Share_ptr, which is designed to mimic the behavior of a pointer through a class, and provides a function that the pointer does not have, that is, when the pointer variable is scoped, the function of the memory that the pointer points to is automatically processed. So the Shareptr template class you see above is the equivalent of a proxy class.

What about the Realsubject class? Since the smart pointer is a proxy for pointers, the Realsubject class is of course the member variable T in shareptr<t>, and I think it is more appropriate to say that the pointer t* is of type T. Haha, wonderful!

So what about the subject class? What does this place serve as this class? From the class diagram of the proxy pattern, you can see that the subject class defines a common interface between the Realsubject and the proxy, you think, since Realsubject is a pointer, then it's operation is *,, = =,! = and = These five kinds, Since these operations are inherently native operations and are not special rules, there is no such subject here, but you can see that these common interfaces, or operations, are implemented in the Shareptr class above.

In other words, *,-=, = =,! =, and = These five operations are interfaces in the subject class, but there is no need to implement a subject base class, and then let shareptr inherit it. Because pointers do not need to inherit subject, they already have these five types of operations. So here we have omitted this class.

Now you should understand why a class here is a proxy mode. In fact, I think the most important thing in learning the design pattern is to learn its thinking, to learn how to solve the problem and how to use it to structure our program, instead of mechanically the class diagram or its definition. The smart pointer above is an example.

In fact, a smart pointer is not a pointer variable, it is just an object defined on the stack, which behaves like a pointer variable by operator overloading. When the program runs out of its scope, the destruction is destroyed and the corresponding operation is performed. Here's a quick look at what extra things this agent has done for us.

For example, when an object is disposed, the following actions are performed:

Template <typename t>shareptr<t>::~shareptr () {    _decused ();} Template <typename t>void shareptr<t>::_decused () {    --*_used;    if (*_used ==0)    {        if (_ptr!= NULL)        {            delete _ptr;            _ptr= NULL;        }        Delete _used;        _used = NULL;}    }

More implementations and additional operations to view the source code.

Six, Android the proxy mode in

In Android, the proxy mode is also widely used, for example, the Activitymanagerproxy class is a proxy, it is the agent of Activitymanagernative, That is to say Activitymanagerproxy is the proxy class above, and activitymanagernative is equivalent to Realsubject class, they all have a common interface Iactivitymanager.


There is also an important class here: Activitymanager, which corresponds to the client in the class diagram of the proxy pattern. In this class, you can see a large number of getxxx functions, which are called to the Getdefault () method of the Activitymanagernative class, and the method obtains a common singleton iactivitymanager reference. The implementation in the proxy is then invoked through polymorphism.


Note: Due to the relationship between time, not in-depth study.


Seven, Code Address

http://download.csdn.net/detail/ljianhui/7468509

Related Article

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.