


What is the adapter pattern (Adapter) in Java? Adapter pattern (detailed explanation)
What this article brings to you is what is the adapter mode (Adapter) in Java? Adapter pattern (detailed explanation). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
Purpose: Adapt the source type to the target type to meet the needs of the client (Client); here we regard the caller of the target interface as the client
Usage scenarios: In scenarios where the type needs to be converted from source type to target type
Preconditions:Existing client
//Client 一个调用目标接口的方法 Class ClientInvoking { static void invoke(TargetInterface target) { String value = target.getMark(); System.out.println(value); } }
Several commonly used modes
Mode 1: There is a target interface and there are existing methods
//目标接口 public interface TargetInterface { public String getMark(); public String getInfo(); }
//已有类及方法 public class ExistClass { public String sayHello() { return "Hello"; } public String sayWorld() { return "World"; } }
We assume that the string returned by ExistClass is exactly what our client needs to use, but the client needs It is obtained through an object of TargetInterface type, so we need to find a way to adapt the existing class so that it can meet the needs of the client; there are two application solutions in this mode:
solution 1. Class adapter mode
//适配器 public class ClassAdapter extends ExistClass implements TargetInterface { public int getMark() { String value = this.sayHello(); return value; } public int getInfo() { String value = this.sayWorld(); return value; } }
//客户端调用 TargetInterface target = new ClassAdapter(); ClientInvoking.invoke(target);
It can be seen from the concept of Java interface that ClassAdapter, as the implementation class of TargetInterface, can be transformed upward into the TargetInterface type to adapt to the needs of the client.
Scheme 2. Object Adapter Pattern
//适配器 public class ClassAdapter implements TargetInterface { private ExistClass exist; public ClassAdapter(ExistClass existClass) { this.exist = existClass; } public int getMark() { String value = exist.sayHello(); return value; } public int getInfo() { String value = exist.sayWorld(); return value; } }
//客户端调用 TargetInterface target = new ClassAdapter(new ExistClass()); ClientInvoking.invoke(target);
This scheme is similar to the class adapter pattern, except that it does not use inheritance but uses the method of holding objects. , more flexible and more scalable.
Mode 2: There is no target interface, but there is a target class, and there are existing methods
Let’s first check the preconditions The client is modified as follows:
Class ClientInvoking { static void invoke(TargetClass target) { String value = target.getMark(); System.out.println(value); } }
After the transformation, the invoke method requires an object of the TargetClass class as a parameter; the following are the target class and existing classes
//目标类 public class Class { public String getMark() { return "yes"; } public String getInfo() { return "no"; } }
//已有类及方法 public class ExistClass { public String sayHello() { return "Hello"; } public String sayWorld() { return "World"; } }
We assume that the string returned by ExistClass is exactly what our client needs to use, and the content of the TargetClass object required by the client is outdated, so we need to adapt ExistClass in a way to suit the client. The needs of the client;
//适配器 public class ClassAdapter extends TargetClass { private ExistClass exist; public ClassAdapter(ExistClass existClass) { this.exist = existClass; } public int getMark() { String value = exist.sayHello(); return value; } public int getInfo() { String value = exist.sayWorld(); return value; } }
//客户端调用 TargetClass target = new ClassAdapter(new ExistClass()); ClientInvoking.invoke(target);
In this mode, two classes are designed, and finally upward transformation is required. According to Java's single inheritance mechanism, we can only hold the object through form, the object adapter pattern.
Mode 3: Default adapter mode
In this mode, there is no explicit target type, but only the source type; So we need to use this, often because the source type provides too many things that we don't need, and we need to customize it through the adapter mode. Take WindowListener as an example to explain:
//WindowListener源码 public interface WindowListener extends EventListener { public void windowOpened(WindowEvent e); public void windowClosing(WindowEvent e); public void windowClosed(WindowEvent e); ... }
//添加监听器的例子 Frame frame = new Frame(); frame.addWindowListener(new WindowListener() { @Override public void windowOpened(WindowEvent e) { } @Override public void windowClosing(WindowEvent e) { } @Override public void windowClosed(WindowEvent e) { } ... })
Such code seems very cumbersome; for example, I only need to listen to the closing event, but a lot of template code is generated that has nothing to do with it. Reduces the readability of the code. In view of this, we will customize it and only listen to one interface;
We first provide an abstract class to implement the interface, and provide all listeners with Provide an empty implementation; then use a subclass of the abstract class to rewrite the implementation of the listener for which the window is closing. The code is as follows:
//适配器 public abstract ListenerAdapter implements WindowListener { public void windowOpened(WindowEvent e) {} public void windowClosing(WindowEvent e) {} public void windowClosed(WindowEvent e) {} ... }
//重写方法 public class OverrideWindowClosing extends ListenerAdapter { @Override public void windowClosing(WindowEvent e) { //TODO } }
//客户端调用 frame.addWindowListener(new OverrideWindowClosing());
This method simplifies the interface and improves the readability of the code. sex. The most important thing is that we have realized the customization of the interface and can only do the things we care about.
Summary: The above is the entire content of this article, I hope it will be helpful to everyone's study. For more related tutorials, please visit Java video tutorial, java development graphic tutorial, bootstrap video tutorial!
The above is the detailed content of What is the adapter pattern (Adapter) in Java? Adapter pattern (detailed explanation). For more information, please follow other related articles on the PHP Chinese website!

Start Spring using IntelliJIDEAUltimate version...

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

Java...

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to set the SpringBoot project default run configuration list in Idea using IntelliJ...


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.