Novice Java design mode-adapter mode, decoration mode, proxy mode similarities and differences

Source: Internet
Author: User

Section before the 3 design patterns to share the learning experience, respectively, is the adapter mode, decoration mode, Agent mode.

But it seems that the more you write the more confused, these three models have some very similar places, always some confused.

Today, we will study again and share the learning experience with you. This is a combination of my work in the actual project.


Design patterns, in fact, is a solution, Java as an object-oriented language, for all design patterns in the implementation, always without the implementation of the interface, the inheritance of the abstract class, sometimes seems to be to implement the interface and write interface, so in the three modes of the description code, We all define the interface, so we have the confusion now.


First of all, introduce the concept of these three kinds of design patterns.

Adapter mode, an adaptation allows classes that are usually incompatible with interfaces to work together, wrapping the class's own interface in an existing class.

Decorator mode, the original can not meet the existing needs, the original to enhance .

Proxy mode, the same class that calls the method of another class, does not directly manipulate this method.


The adapter is characterized by compatibility, and from the code features, the adapter class has the same interface as the original class and holds a new target object.

Like a three-hole to 2-hole adapter, he has a three-hole plug that plugs into a three-hole receptacle, and a two-hole receptacle can be inserted by a 2-hole plug.

The adapter mode is to retrofit the original 3 holes.

When using the adapter mode, we must also hold the original object, the matching object, the target object ....


The adorner pattern is characterized by an enhancement, and his characteristic is that the decoration class and all decoration classes must implement the same interface, and must hold the object that is adorned and can be infinitely decorated.


The proxy mode is characterized by isolation, isolating the relationship of the calling class and the called class, and invoking it through a proxy class.


In general, the following three sentences are spoken:

1 The adapter pattern is to convert a class (a) into another class (b) in some way.
2 decoration mode adds some new functionality to another class (b) on the basis of an original class (a).
3 The proxy mode is to convert a class (a) into a specific operation class (b).


It's Luo Li again. A big paragraph, then we happily came to the example of time, this is a practical example of work.


A brief introduction, the company has an order system, dedicated to provide order management interface, provided to the store, WAP Mall, mobile phone apps, such as client calls.


When the order system is on line, it already contains a very complete data operation.


Now mobile phone apps need to upgrade, the old interface may not meet the demand, such as the original order pickup extension validity of the interface needs to provide up to time and order number, the new app may not provide up to the time, only need to provide order number to extend the time.


And the old interface can not be modified, because the old order interface is for all platforms, then the new interface requirements must be adapted to the original interface ...


The solution is as follows: New Appadepter class, used to adapt the old interface, while developing to a new interface ....

First, the original interface and the implementation class are given.

Original interface:

/** * Original interface, need to pass in OrderId, time * */public interface Sourceorderapi {public void updatedate (String orderid,string date,string CLI ENT);}

Implementation class:

public class Sourceorderapiimpl implements sourceorderapi{@Overridepublic void Updatedate (String orderId, String date, String Client {System.out.println (client+) extended the validity period of order "+orderid+" to "+date";}}

In this set of code, it is necessary for the client to pass in OrderID and expiration date and client name to extend ...

Main method:

public class Test {public static void main (string[] args) {Sourceorderapi Sourceorderapi = new Sourceorderapiimpl (); source Orderapi.updatedate ("123456", "2014-10-15", "User");}}

Operation Result:



For the new interface, the client does not have to pass in the date parameter

Public interface Apporderapi {//requires only an incoming order ID to be public void Updatedate (String orderid,string client);}

The new implementation class:

public class Apporderapiimpl implements APPORDERAPI{SOURCEORDERAPI Sourceorderapi;public Apporderapiimpl () { Sourceorderapi = new Sourceorderapiimpl ();} @Overridepublic void Updatedate (String orderid,string client) {//The method here is arbitrary, but is guaranteed to be fully compatible with the original, is to guarantee the invocation of the original interface Sourceorderapi.updatedate (OrderId, "9999-12-31", client);}}

Main method:

public class Test {public static void main (string[] args) {Apporderapi Apporderapi = new Apporderapiimpl (); apporderapi.upd Atedate ("123456", "User");}}

Operation Result:



In this set of code, the new implementation class holds the object of the old interface, which is to put this object new ...

Then in the new method, the adaptation operation is performed.

And here the so-called adaptation is compatible with the old interface and compatible with the new interface.

Compatible with the old interface is very simple, is to call the old method directly.

and a compatible new interface is the business logic you're going to do ...

For example, I have done a relatively simple operation, the application of the unified introduction of "9999-12-31", these are based on specific project requirements to implement your business code.

Seeing this, many people would think that such code is not very common ....

I have been deliberately to go over my previous code, a lot of similar writing ...

In fact, design patterns are often incorporated into our code, but we do not understand this mode, so even if you write it yourself, do not know that this is an adapter mode ...

Design pattern is a kind of thought, he does not have the fixed implementation code, I extensively consulted many big God's adapter pattern explanation, everybody all coincidentally mentioned the class adaptation and the object adaptation, in the code has the implementation inheritance such wording. Of course, these great gods are more standard in their writing ...

But take a closer look at the GOF adapter mode explanation.



Only need to convert the original interface to the customer wants another interface, is the adapter mode!

Conversion is nothing more than 1. Inherit the original class or implement the original interface 2. The object holding the original interface

Achieve the target interface again ....

Then the first is the adaptation of the class, the second is the adaptation of the Object! That's all ....


Then back to the proxy mode, the code, and the adapter mode has a similar place!

For example, now our company's system to upgrade, our original interface did not join security mechanism, resulting in anyone can call this interface, now the company needs to transform this interface, only it can only be called by the admin, the other users must enter the account password to call

Then the above original interface and class do not need to change, we only need to add the agent can ...

Here will show the proxy mode and the maximum difference between the adapter mode, the proxy mode is the same interface with the original object implementation, and the adapter class is to match the new interface, plainly, implement a new interface.

Proxy class:

public class Proxysourceorderapiimpl implements SOURCEORDERAPI {Sourceorderapi sourceorderapiimpl;public Proxysourceorderapiimpl () {Sourceorderapiimpl = new Sourceorderapiimpl ();} @Overridepublic void Updatedate (String orderId, string date, string client) {//To determine if the admin is updated otherwise let it enter the account password if ("admin". Equals (client) {sourceorderapiimpl.updatedate (orderId, date, client);} Else{system.out.println ("account is not admin, no query permissions, please enter the admin operation");}}}

Main method:

public class Test {public static void main (string[] args) {Sourceorderapi Proxysourceorderapiimpl = new Proxysourceorderap Iimpl ();p roxysourceorderapiimpl.updatedate ("123456", "2014-10-15", "user");p roxysourceorderapiimpl.updatedate (" 123456 "," 2014-10-15 "," admin ");}}
Operation Result:


The proxy class here must hold the object to implement the original interface and hold the original interface in order to be called the proxy class.

In this way, we do not need to modify the original implementation class, with a proxy class to filter. Some people may have such doubts, why not directly modify in the original implementation class, remember the basic principles of Java design pattern, close the modification internally.

If you do not have the other class, others just provide you with such an operational jar package how do you do it? Decompile the jar package, and then modify it? And if some places can call the original interface directly, if you modify the original implementation of the class, it is not to other places also caused the impact? Cannot modify the original code this is the basic principle.


Finally, is the adorner mode, the adorner mode and relative to the above 2 modes better understand, the difference is the largest.

If said, now this extension order, not only can extend the order delivery period, can extend the return period of the order.

This is a typical decorator, what you need to do is to enrich the functionality of the original interface, and do not change the original interface.

public class Newsourceorderapiimpl implements SOURCEORDERAPI {Sourceorderapi sourceorderapi;public Newsourceorderapiimpl (Sourceorderapi sourceorderapi) {this.sourceorderapi = Sourceorderapi;} @Overridepublic void Updatedate (String orderId, string date, string client) {sourceorderapi.updatedate (orderId, date, Client); System.out.println (client+ "has extended the refund period of order" +orderid+ "to" +date ");}
Main method:

public class Test {public static void main (string[] args) {Sourceorderapi Sourceorderapi = new Newsourceorderapiimpl (New S Ourceorderapiimpl ()); Sourceorderapi.updatedate ("123456", "2014-10-15", "User");}}
Operation Result:

In adorner mode, you must have classes that are decorated and decorated. In this set of code, the original Sourceorderapi object is the decorated class, and the new Newsourceorderapiimpl is the decoration class, the adornment class must pass the decorated object as a parameter.

This is different from the proxy mode code, the proxy mode must be itself holding this object, do not need to be imported from outside. and the decoration mode must be imported from the outside, and can not order, according to the actual needs of the code to pick the order, as you eat hot pot first put cabbage or put meatballs can.


From the perspective of use, the agent mode is focused on the isolation limit, so that external access to your actual calling object, such as permission control, decoration mode is focused on the expansion of the function, in the same way to achieve more functions.


It's a big piece of paper, probably a good collation of these three patterns, and the individual itself is thoroughly understanding the three patterns.

Now it is safe to go to the next link to learn ...

Hastily 拙笔, if there is a mistake, please point out



Novice Java design mode-adapter mode, decoration mode, proxy mode similarities and differences

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.