Adapter pattern of design pattern in Java

Adapter pattern of design pattern in Java

preface:

The adapter pattern can apply a class or interface to another different but related interface. The main method is to declare the implementation class of a target interface, In this class, declare a constructor and an instance of the Adaptee that takes the Adaptee class or interface (Adaptee) as a parameter, so that the instance of the Adaptee can be called when implementing the target interface, supplemented by some additional operations. The main body of the adapter mode has three parts: adapter, adapter implementation class and Adaptee. The specific class structure is shown in the following figure:

Here, the object of the Adaptee is put into the adapter class in a combined way, so the Adaptee and its implementer can use the adapter. The advantage of adapter mode is that it can be compatible with different types of objects with similar work purposes, while the disadvantage is that if the target interface is large, it requires a lot of additional code to carry out compatibility work.

Here is a less realistic example to illustrate the adapter pattern. Turkeys and ducks can call and fly, but turkeys and ducks call differently, and turkeys don't fly as far as ducks. If you want to disguise a turkey as a duck, you need to dress up the turkey object. Here we can declare a dress class, which is also a duck type. When the turkey enters the dress, it becomes a duck. The specific class implementation is as follows:

Target interface (duck interface):

Normal implementation of target interface (duck Implementation):

Adapter interface (Turkey interface):

General implementation of the Adaptee (Turkey):

Adapter:

Through the turkey adapter, we adapted the Turkey into a duck. It should be noted here that both the adapter mode and the decorator mode decorate the source object to achieve a certain effect, but the difference between the adapter mode and the decorator mode is that the adapter mode adapts the source object to make it conform to a specific interface, and the decorator mode is an extension of the function of the source object to make it do more work.

If you have any questions, please leave a message or go to the community of this site for exchange and discussion. Thank you for reading. I hope it can help you. Thank you for your support to this site!

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>