[Original-tutorial-serialization] "android big talk design mode"-structural mode of design mode Chapter 1: proxy mode QQ chat Robot

Source: Internet
Author: User
<Big talk design model> description and copyright notice of this tutorial

Guoshi studio is a technical team dedicated to enterprise-level application development on the Android platform. It is committed to the best Android Application in China.ProgramDevelopment institutions provide the best Android enterprise application development training services.

Official contact information for Enterprise Training and Development Cooperation:

Tel: 18610086859

Email: hiheartfirst@gmail.com

QQ: 1740415547

QQ: 148325348

Guoshi studio is better for you!

L this document references and uses free images and content on the Internet, and is released in a free and open manner, hoping to contribute to the mobile Internet and the smart phone age! This document can be reproduced at will, but cannot be used for profit.

L if you have any questions or suggestions about this document, go to the official blog

Http://www.cnblogs.com/guoshiandroid/ (with the following contact information), we will carefully refer to your suggestions and modify this document as needed to benefit more developers!

L The latest and complete content of "big talk design mode" will be regularly updated on the official blog of guoshi studio. Please visit the blog of guoshi studio.

Http://www.cnblogs.com/guoshiandroid/get more updates.

Proxy ModeQqCHATBOT 

Proxy ModeUse Cases: 

When chatting with your own mm on the internet, you will always encounter harassment from other mm. At the beginning, it is always "hi, hello", "Where are you from ?", "How old are you ?", "How tall ?" These words are really annoying. I want to write a QQ robot program as my proxy. When I receive these words, I have set up an automatic answer. When I receive other words, I will be notified of the answer. How should I do, cool. In fact, for other mm, whether I am myself or my robot, she thinks it is just a "chat guy", but I am a lot easier. In this way, we can have a good chat with our own mm, so that we can enjoy the first love of moisturizing ^_^

Proxy mode explanation:

Proxy pattern is one of the Design Patterns of constructor. Proxy Pattern provides a proxy object for an object and controls the reference to the source object by the proxy object. One person or one institution takes some action in place of another person or another institution to control access to this object.
The so-called proxy refers to a class with the same interface as the proxy element (the object to be proxy). The client must interact with the target class of the proxy through the proxy, proxy generally performs some special processing in the process of interaction (before and after interaction.

Provide a surrogate or placeholder for another object to control
Access to it.

Proxy ModeUMLFigure:

The proxy mode involves the following roles:

Abstract topic role: a common interface between a real topic and a proxy topic.

Realsubject role: defines the real objects represented by the proxy role.

Proxy topic (proxy) role: it contains references to the real topic role. The proxy role usually performs some operations before or after passing the client call to the real topic object, instead of simply returning real objects.

The UML diagram of the proxy mode is as follows:

 

In-depth analysis of proxy Mode:

The proxy mode provides a proxy for other objects to control access to this object. In some cases, the customer does not want or cannot directly reference an object, but the proxy object can play a mediation role between the customer and the target object, remove content and services that the customer cannot see or add additional services required by the customer.

So when should I use the proxy mode? When you use an existing method, you need to improve or modify the original method. At this time, there are two ways to improve: modify the original method to adapt to the current usage, or use a "third party" method to call the original method and control the results of the method. The first method obviously violates the principle of "opening to extension and disabling modification", and modifications made to the original method may blur and diversify the functions of the original class, the second method can be used to clarify the function division and facilitate subsequent maintenance.

Of course, if it is a very small system, and the functions are not very complex, then the use of proxy mode may seem bloated, not as fast as the first method. This is like a three-person house. It is quite reasonable to have all the housework done by a housewife or a nanny. There is no need to hire several nanny agents at all.

According to the classification of proxy modes in Java and patterns, there are eight types of proxy modes. Here we will list several common and important ones as follows:

Remote Proxy: provides a Local Area Representative object for an object in a different address space. For example, you can create a machine in a certain corner of the world as a part of your LAN through proxy.

Virtual Proxy: a virtual proxy is created only when a real need for high resource consumption or complex object latency is required. For example, if a large image takes a long time to be displayed, you can use the editor or browser to open the image when it is included in the document, this large image may affect reading the document. In this case, you need to create an image proxy to replace the real image.

Copy-on-write Proxy: a virtual proxy. Delays replication until the client needs it.

Protection (protect or access) proxy: controls access to an object. For example, in a forum, different identities have different permissions for Logon. You can use the proxy mode to control permissions (of course, other methods can also be used ).

Cache Proxy: provides a temporary storage space for the results of a target operation so that multiple clients can share the results.

Firewall Proxy: protects the target from malicious users.

Synchronization Proxy: enables several users to simultaneously use an object without conflict.

Smart reference Proxy: provides additional services for comparing target objects. For example, record the access traffic (this is a simple example) and provide some friendly tips.

Proxy mode is a useful mode. It can coordinate callers and callers, and reduce the Coupling Degree of the system to a certain extent.

Use Case Analysis and proxy ModeCodeImplementation:

In the above application scenario, the power plug of the MM laptop cannot be used normally, that is, the plug of the notebook does not match the interface of the MM school dormitory, so GG went to the market and bought a converter suitable for the MM notebook and dormitory Power interface. The converter plug is the adapter.

 

Create an abstract role:

Package
Com. diermeng. designpattern. proxy;

/**

*Abstract roles, providing public interfaces for proxy classes and specific classes

*

*/

Public interface
Chat {

 

Public void reply (string message );

}

Create a specific role class:

PackageCom. diermeng. designpattern. Proxy. impl;

 

ImportCom. diermeng. designpattern. Proxy. Chat;

 

/**

* Specific role class: the proxy class

*

*/

Public ClassMychatImplementsChat {

 

Public VoidReply (string message ){

 

System.Out. Println ("the content I need to reply to myself... ");

}

}

 

Create a proxy class:

PackageCom. diermeng. designpattern. Proxy. impl;

 

ImportCom. diermeng. designpattern. Proxy. Chat;

/**

* Proxy class, holding a reference to the proxy class

*

*/

Public ClassChatproxyImplementsChat {

 

PrivateChat mychat =NewMychat ();

 

Public VoidReply (string message ){

 

If(Message. Equals ("hi, hello ")){

System.Out. Println ("Hi, you ");

}Else If(Message. Equals ("where did you come from? ")){

System.Out. Println ("I'm from China! ");

}Else If(Message. Equals ("How old are you? ")){

System.Out. Println ("I'm 22 this year! ");

}Else If(Message. Equals ("How tall? ")){

System.Out. Println ("My height 178 ");

}

Else{

Mychat. Reply (Message );

}

}

}

 

Create a test client:

PackageCom. diermeng. designpattern. Proxy. client;

 

ImportCom. diermeng. designpattern. Proxy. Chat;

ImportCom. diermeng. designpattern. Proxy. impl. chatproxy;

 

Public ClassProxytest {

 

Public Static VoidMain (string [] ARGs ){

// Directly call the proxy class

Chat CP =NewChatproxy ();

 

// The implementation provided by the proxy class

CP. Reply ("hi, hello ");

CP. Reply ("where did you come from? ");

CP. Reply ("How old are you? ");

CP. Reply ("How tall? ");

 

// Implementation provided by specific classes

CP. Reply ("do you like me? ");

}

}

The running result is as follows:

Hi, you too

I'm from China!

I'm 22 this year!

My height 178

What I need to reply to myself...

 

If you want to use the proxy mode according to the above method, the real role must exist beforehand and use it as the internal attribute of the proxy object. However, in actual use, a real role must correspond to a proxy role. If a large number of roles are used, the class will expand sharply. In addition, if you do not know the real role, how can you use the proxy? This problem can be solved through the dynamic proxy class of Java.

The Java Dynamic proxy class is located under the java. Lang. Reflect package and generally involves the following two classes:

(1). Interface invocationhandler: this interface defines only one method object: invoke (Object OBJ, method,
Object [] ARGs ). In actual use, the first parameter OBJ generally refers to the proxy class, and the method is the method to be proxy. This abstract method is dynamically implemented in the proxy class.

(2). Proxy: this class is a dynamic proxy class, which mainly includes the following content:

Protected
Proxy (invocationhandler h): constructor.

Static class
Getproxyclass (classloader loader, class [] interfaces): obtains a proxy class. loader is the class loader, and interfaces is the array of all interfaces of the real class.

Static object newproxyinstance (classloader
Loader, class [] interfaces, invocationhandler h): returns an instance of the proxy class, the returned proxy class can be used as a proxy class (the method declared in the subject interface of the proxy class can be used ).

Dynamic proxy is such a class: it is a class generated at runtime. You must provide a set of interfaces to it when generating it, then the class declares that it implements these interfaces. Of course, you can use the class instance as any of these interfaces. Of course, this dynamic proxy is actually a proxy, and it will not do substantial work for you. When generating its instance, you must provide a handler to take over the actual work.

When using dynamic proxy classes, we must implement the invocationhandler interface. In this way, the realsubject object can be dynamically changed at runtime, and the subject interface to be controlled can be changed at runtime (dynamicsubject class) it can also be dynamically changed to achieve a Flexible Dynamic proxy relationship.

Advantages and disadvantages of proxy mode:

In general, the proxy mode can be used to control access to an object without changing the original code function. This division of labor also reflects the single responsibility principle.

Remote Proxy: This allows the system to hide network details so that the client does not have to consider the existence of the network.

The customer can think that the proxy object is local rather than remote, and the proxy object undertakes most of the network communication work.

Virtual Proxy: The advantage is that the proxy object can be loaded by the proxy object only when necessary. The agent can optimize the loading process as necessary. When loading a module is very resource-consuming, the advantages of virtual proxy are very obvious.

Protection Proxy: It can check the user's permissions at run time, and then decide to pass the call to the proxy object after verification.

Intelligent reference Proxy: You can perform housekeeping operations when accessing an object.

Introduction to the actual application of proxy mode:

The proxy mode is generally used in the following situations:

A large object, such as a large image, takes a long loading time.

A computing result that takes a long time to complete and needs to display intermediate results during the computing process.

It takes a long time to load a remote object on a remote computer, especially during the network transmission peak.

The user has only limited access permissions to the object. In this case, the proxy mode can verify the user's permissions.

Tip:

in some cases, the customer does not want or cannot directly reference an object. In this case, the proxy class is used. The proxy object can play a mediation role between the customer and the target object, the client does not know the difference between a proxy object and a real object. The proxy mode does not know the real proxy object, but only holds an interface of the proxy object, at this time, the proxy object cannot be created as a proxy object, and the proxy object must have other roles created and passed in on behalf of the proxy object.

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.