Proxy Mode with Android

Source: Internet
Author: User

Agent mode (proxy)


First, What is proxy mode

Let's take a look at the official saying that the proxy mode is to provide a proxy for other objects to control access to this object.

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

In fact, the term agent is not unfamiliar to us, there are a lot of examples of agents in life. such as campus agents, on behalf of the campus, the campus agent is for his corresponding boss of the agent, and this campus agent's job is to visit students on campus, such as the students to carry out questionnaires and so on. In this example, the student is the other object of the official statement, the campus agent's supervisor control the student's access by controlling the campus agent. This should be a little clearer.


Second, class diagram for proxy mode


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

The above-mentioned campus agent for example, we come to see the proxy model of the wind, 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 the three classes of subject, Realsubject, and Proxy, and the Dosurvey method in these classes is equivalent to the request method in.

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

In fact the modern code is for example the following (Proxy.cpp):

1, the Worker class definition, for example, it has a Dosurvey interface

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

2, the Boss class definition, for example, 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, Schoolproxy class definition, for example, it inherits the worker class, and implements the Dosurvey interface, which maintains a reference to the object of a boss class, and calls the boss's 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. However, 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 methods such as the following:

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 to help its boss to complete the investigation work.

Four, Application of proxy mode

Look at the above code, I think the operation and principle of proxy mode, everyone almost the same can understand, but in fact, there is not only 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, and its example is webserver.

2) Virtual Agent

It creates more expensive objects based on requirements, and it stores the real objects that need to be instantiated for a very long time. For example, when we browse the Web page, there may be some of the larger picture, although the picture is larger, but you can still open the page very quickly, but the picture can not be displayed in the first time, it may be in a few seconds after the ability to display normally, here is the virtual agent to replace the real picture.

3) Protection agent

It is used to control access to the original object, while the protection agent should have different permissions for the object.

4) Smart Reference

It is used to mean that when a real object is called, the agent runs extra actions to handle something else. For example, a smart pointer in C + +, instead of a simple pointer, it will run some extra action 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 think that the proxy mode does not work, then you are wrong, to come down to see the above four kinds of proxy mode of the powerful use of a smart reference.

have used C + + program Ape, definitely know smart pointer this good thing, it can make greatly reduce our memory management difficulty, because it through the object management resources, so that the pointer to the heap memory like stack memory, can self-release.

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 just so many definitions, and by looking at the definition above, you can ask questions, does this really apply the above-mentioned proxy model? The above proxy mode is not to have a subject class, a Realsubject class, and a proxy class? and Realsubject class and Proxy is subject subclass, need to define subject interface? Why is there only a class here?

Now you don't see it, I don't blame you. It will be clear when you look down.

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, it proactively handles the function of the memory that the pointer points to. 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 the proxy of the pointer, 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, strange!

So what about the subject class? What does this place serve as this class? From the proxy mode class diagram can see the subject class definition is the Realsubject and proxy common interface, you think, since Realsubject is a pointer, then its operation is *,, = =,! = and = These five kinds of, Since these operations are inherently native operations and are not special rules, there is no such subject here, but it is possible to 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. Since pointers do not need to inherit subject, they already have these five operations. So here we have omitted this class.

Now you should make it clear why one of the classes here is a proxy mode. In fact, I think the most important thing in learning a design pattern is to learn its ideas, learn how to solve the problem and how to use it to structure our program, rather than mechanically the class diagram or its definition. The smart pointer above is a sample.

In fact, a smart pointer is not a pointer variable, it is simply 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 run. 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;}    }

Many other implementations and additional operations to view the source code.

Six, Android the proxy mode in

In Android, the proxy mode is also widely used, such as 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 the Realsubject class, they all have a common interface Iactivitymanager.


Here is another important class: 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

Proxy Mode with Android

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.