The adapter pattern I know of design patterns

adapter pattern know design patterns


Introduction


What we're going to talk about next is Java One of the best design patterns : Adapter pattern

If this is your first trip abroad to the United States , You will find that the standard of power plug and socket in America is different from that in China . At this time, you need to buy American plug and socket .

If you go abroad to Germany for the second time , In Germany, I found that the American plug did not match the German socket

image.png

At this time, we need to buy a power adapter that provides both American standard socket and European standard plug to solve this problem

One 、 What is adapter mode

Adapter pattern (Adapter Pattern): Convert the interface of a class to another interface representation that the client expects .

The purpose of the Lord is Compatibility , Allows two classes that would otherwise not work together because of interface mismatches to work together . It is alias wrapper (Wrapper)

Adapter mode belongs to structural mode

It is mainly divided into three categories : Adapter like pattern 、 Object adapter pattern 、 Interface adapter mode

Two 、 working principle


Adapter pattern : Convert the interface of one class to another . Make classes that are not compatible with the original interface compatible

From the user's point of view Can't see the Adaptee , It's decoupled

user Call the target interface method converted by the adapter , The adapter then calls the relevant interface methods of the adapter

User received Feedback results , It just feels like interacting with the target interface , Pictured

image.png

3、 ... and 、 Adapter like pattern

There is one Adapter By inheritance src class , Realization dst The class interface , complete src->dst The adaptation of .

Application examples

Take the example of charger in life to explain adapter :

  • The charger itself is equivalent to Adapter
  • 220V Alternating current is equivalent to src ( That is, the adapted )
  • Our eyes dst( That's the goal ) yes 5V DC voltage

image.png

According to the idea of class adapter , Our class diagram is like this

image.png

According to our thinking , So let's create one 220v The output voltage of power supply class

// The adapted class
class Voltage220V {
// Output 220V The voltage of
public int output220V() {
int src = 220;
System.out.println(" voltage =" + src + " v ");
return src;
}
}

Next, we provide mobile phones to use 5v voltage , For the output

// Adapter
interface IVoltage5V {
public int output5V();
}

So we need an adapter class to 220v Blood pressure reduced to 5v The voltage of

// The adapter class
class VoltageAdapter extends Voltage220V implements IVoltage5V {
@Override
public int output5V() {
// Get 220V voltage
int srcV = output220V();
int dstV = srcV / 44 ; // The depressurization treatment turns into 5v
return dstV;
}
}

Then we can let the phone through the adapter , It's charging

class Phone {
// Charge
public void charging(IVoltage5V iVoltage5V) {
if (iVoltage5V.output5V() == 5) {
System.out.println(" Voltage is 5V, It can be charged ~~");
} else if (iVoltage5V.output5V() > 5) {
System.out.println(" The voltage is greater than 5V, Can't charge ~~");
}
}
}

Now let's look at this demo How does it work ?

public static void main(String[] args) {
System.out.println(" === Adapter like pattern ====");
Phone phone = new Phone();
phone.charging(new VoltageAdapter());
}
The operation results are as follows :
=== Adapter like pattern ====
voltage =220 v
Voltage is 5V, It can be charged ~~

Class adapter pattern considerations and details

Java It's a single inheritance mechanism , So the class adapter needs to inherit src This is a disadvantage , Because it requires dst It has to be an interface , There are certain limitations ;

src The method of class is Adapter in It'll all come out , It also increases the cost of using .

But it inherited src class , So it can To rewrite as needed src Class method , bring Adapter Increased flexibility 了 .

Four 、 Object adapter

When we talked about class adapters earlier , Find out Need to inherit src class , Added coupling

The object adapter and the class adapter have the same pattern , Just to Adapter Class

We will It's not inheritance src class , It's holding src Class , To solve the problem of compatibility .

namely : hold src class , Realization dst The class interface , complete src->dst The adaptation of

according to “ Synthetic multiplexing principle ”, Try to use relationships in the system ( polymerization ) Instead of inheritance

According to the idea of object adapter , Our class diagram is like this

image.png

According to our thinking , The original output 5v The interface doesn't work , It's the same as before

// Adapter
interface IVoltage5V {
public int output5V();
}

And the original one 220v The output voltage of power supply does not need to be changed

// The adapted class
class Voltage220V {
// Output 220V The voltage of
public int output220V() {
int src = 220;
System.out.println(" voltage =" + src + " v ");
return src;
}
}

Next, we modify the original adapter class , Add constructors to pass in 220v Output class

// The adapter class
class VoltageAdapter implements IVoltage5V {
private Voltage220V voltage220V;
public VoltageAdapter(Voltage220V voltage220V) {
this.voltage220V = voltage220V;
}
@Override
public int output5V() {
int dstV = 0;
if(null != voltage220V){
// Get 220V voltage
int srcV = voltage220V.output220V();
dstV = srcV / 44 ; // The depressurization treatment turns into 5v
System.out.println(" Adaptation complete , The output voltage is :" +dstV);
}
return dstV;
}
}

Then we can let the phone through the adapter , It's charging

class Phone {
// Charge
public void charging(IVoltage5V iVoltage5V) {
if (iVoltage5V.output5V() == 5) {
System.out.println(" Voltage is 5V, It can be charged ~~");
} else if (iVoltage5V.output5V() > 5) {
System.out.println(" The voltage is greater than 5V, Can't charge ~~");
}
}
}

Now let's look at this demo How does it work ?

public static void main(String[] args) {
System.out.println(" === Adapter like pattern ====");
Phone phone = new Phone();
phone.charging(new VoltageAdapter(new Voltage220V()));
}
The operation results are as follows :
=== Adapter like pattern ====
voltage =220 v
Adaptation complete , The output voltage is :5
Voltage is 5V, It can be charged ~~

Object adapter pattern considerations and details

Object adapters and class adapters are actually The same idea , But in a different way .

according to Synthetic multiplexing principle , Use combination instead of inheritance , So it Solved the problem that class adapter must inherit src The limitations of , No longer ask for dst It has to be an interface .

Use A lower cost , More flexible

5、 ... and 、 Interface adapter mode

Some books are called : Default adapter mode ( Selective )

The core idea : When you don't need to implement all the methods provided by the interface , You can design an abstract class to implement the interface , And for Each method in the interface provides a default implementation ( Empty method ), Then the subclass of the abstract class can selectively override some methods of the parent class to implement the requirements

Apply to An interface doesn't want to use all its methods The situation of

Application examples

stay Android Medium Attribute animation ValueAnimator Class can pass through addListener(AnimatorListener listener) Method add listener

The general way of writing is as follows :

ValueAnimator valueAnimator = ValueAnimator.ofInt(0,100);
valueAnimator.addListener(new Animator.AnimatorListenerO{
// Default implementation ( Empty method )
@Overmride
public void onAnimationStant(Animator animation){}
// Default implementation ( Empty method )
@Ovemide
public void onAnimationEnd(Animator animation){}
// Default implementation ( Empty method )
@Overide
public void onAnimationCancel(Animator animation){}
// Default implementation ( Empty method )
@Ovemide
public woid onAnimationRepeat(Animator animation){}
});

Sometimes we don't want to achieve Animator.AnimatorListener All methods of interface , We just want to monitor onAnimationStart, We will write as follows

ValueAnimator valueAnimator = ValueAnimator.ofInt(0,100);
valueAnimator.addListener(new Animator.AnimatorListenerO{
// Default implementation ( Empty method )
@Overmride
public void onAnimationStant(Animator animation){}
});

EH , Why can we do this , The reason is that an abstract class implements empty methods by default

First, our interface :AnimatorListener

public static interface AnimatorListener {
void onAnimationStart(Animator animation);
void onAnimationEnd(Animator animation);
void onAnimationCancel(Animator animation);
void onAnimationRepeat(Animator animation);
}

Next, let's make our abstract class :AnimatorListenerAdapter

public abstract class AnimatorListenerAdapter implements Animator.AnimatorListener,
Animator.AnimatorPauseListener {
// Default implementation ( Empty method )
@Overmride
public void onAnimationStant(Animator animation){}
// Default implementation ( Empty method )
@Ovemide
public void onAnimationEnd(Animator animation){}
// Default implementation ( Empty method )
@Overide
public void onAnimationCancel(Animator animation){}
// Default implementation ( Empty method )
@Ovemide
public woid onAnimationRepeat(Animator animation){}
}

That is to say, we make an abstract class , Two interfaces are implemented , And implement the null method by default

That's why we can just write start The method can be , Rewrite the way you care

So our class diagram , In fact, it's just like this , As shown in the figure below

image.png

So let's use demo Experience , First, create an interface

interface Interface4 {
public void m1();
public void m2();
public void m3();
public void m4();
}

At the same time, we create Adapter Abstract classes inherit this interface , Empty methods are implemented by default

// stay AbsAdapter We will Interface4 The default implementation of
abstract class AbsAdapter implements Interface4 {
// Default implementation
@Override
public void m1() {}
@Override
public void m2() {}
@Override
public void m3() {}
@Override
public void m4() {}
}

When we just need to achieve m1 When , You can see demo How it's done ?

public static void main(String[] args) {
AbsAdapter absadapter = new AbsAdapter() {
@Override
public void m1() {
System.out.println(" Use m1 Methods ");
}
};
absadapter.m1();
}
The operation results are as follows :
Use m1 Methods 

Here we use the anonymous inner class approach to achieve m1 that will do , You don't have to implement it all

Definition of anonymous inner class

Let's first look at the syntax format of the definition of anonymous inner classes :

new Implementation interface (){// Anonymous inner class body part }
new Parent constructor ( Argument list ){// Anonymous inner class body part }

The definitions of these two ways correspond to two ways respectively , One is the interface , The other is abstract class .

For implementing interfaces , because Interfaces have no constructors , Note that this must be an empty parameter .

The second is to call The constructor of the parent class , Note that this can be an empty parameter , You can also pass in parameters

Reference material


Silicon Valley : Design patterns ( Mr. Han Shunping ): Adapter pattern

Refactoring.Guru:《 Deep into design patterns 》

版权声明
本文为[twenty-eight thousand six hundred and forty]所创,转载请带上原文链接,感谢
https://javamana.com/2021/01/20210122152848291D.html

  1. 【计算机网络 12(1),尚学堂马士兵Java视频教程
  2. 【程序猿历程,史上最全的Java面试题集锦在这里
  3. 【程序猿历程(1),Javaweb视频教程百度云
  4. Notes on MySQL 45 lectures (1-7)
  5. [computer network 12 (1), Shang Xuetang Ma soldier java video tutorial
  6. The most complete collection of Java interview questions in history is here
  7. [process of program ape (1), JavaWeb video tutorial, baidu cloud
  8. Notes on MySQL 45 lectures (1-7)
  9. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  10. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  11. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  12. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  13. 【递归,Java传智播客笔记
  14. [recursion, Java intelligence podcast notes
  15. [adhere to painting for 386 days] the beginning of spring of 24 solar terms
  16. K8S系列第八篇(Service、EndPoints以及高可用kubeadm部署)
  17. K8s Series Part 8 (service, endpoints and high availability kubeadm deployment)
  18. 【重识 HTML (3),350道Java面试真题分享
  19. 【重识 HTML (2),Java并发编程必会的多线程你竟然还不会
  20. 【重识 HTML (1),二本Java小菜鸟4面字节跳动被秒成渣渣
  21. [re recognize HTML (3) and share 350 real Java interview questions
  22. [re recognize HTML (2). Multithreading is a must for Java Concurrent Programming. How dare you not
  23. [re recognize HTML (1), two Java rookies' 4-sided bytes beat and become slag in seconds
  24. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  25. RPC 1: how to develop RPC framework from scratch
  26. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  27. RPC 1: how to develop RPC framework from scratch
  28. 一次性捋清楚吧,对乱糟糟的,Spring事务扩展机制
  29. 一文彻底弄懂如何选择抽象类还是接口,连续四年百度Java岗必问面试题
  30. Redis常用命令
  31. 一双拖鞋引发的血案,狂神说Java系列笔记
  32. 一、mysql基础安装
  33. 一位程序员的独白:尽管我一生坎坷,Java框架面试基础
  34. Clear it all at once. For the messy, spring transaction extension mechanism
  35. A thorough understanding of how to choose abstract classes or interfaces, baidu Java post must ask interview questions for four consecutive years
  36. Redis common commands
  37. A pair of slippers triggered the murder, crazy God said java series notes
  38. 1、 MySQL basic installation
  39. Monologue of a programmer: despite my ups and downs in my life, Java framework is the foundation of interview
  40. 【大厂面试】三面三问Spring循环依赖,请一定要把这篇看完(建议收藏)
  41. 一线互联网企业中,springboot入门项目
  42. 一篇文带你入门SSM框架Spring开发,帮你快速拿Offer
  43. 【面试资料】Java全集、微服务、大数据、数据结构与算法、机器学习知识最全总结,283页pdf
  44. 【leetcode刷题】24.数组中重复的数字——Java版
  45. 【leetcode刷题】23.对称二叉树——Java版
  46. 【leetcode刷题】22.二叉树的中序遍历——Java版
  47. 【leetcode刷题】21.三数之和——Java版
  48. 【leetcode刷题】20.最长回文子串——Java版
  49. 【leetcode刷题】19.回文链表——Java版
  50. 【leetcode刷题】18.反转链表——Java版
  51. 【leetcode刷题】17.相交链表——Java&python版
  52. 【leetcode刷题】16.环形链表——Java版
  53. 【leetcode刷题】15.汉明距离——Java版
  54. 【leetcode刷题】14.找到所有数组中消失的数字——Java版
  55. 【leetcode刷题】13.比特位计数——Java版
  56. oracle控制用户权限命令
  57. 三年Java开发,继阿里,鲁班二期Java架构师
  58. Oracle必须要启动的服务
  59. 万字长文!深入剖析HashMap,Java基础笔试题大全带答案
  60. 一问Kafka就心慌?我却凭着这份,图灵学院vip课程百度云