Home Java javaTutorial What is the adapter pattern (Adapter) in Java? Adapter pattern (detailed explanation)

What is the adapter pattern (Adapter) in Java? Adapter pattern (detailed explanation)

Oct 18, 2018 pm 04:14 PM
java adapter mode

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

PreconditionsExisting client

//Client 一个调用目标接口的方法
Class ClientInvoking {

    static void invoke(TargetInterface target) {
        String value = target.getMark();
        System.out.println(value);
    }

}
Copy after login

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();

}
Copy after login
//已有类及方法
public class ExistClass {

    public String sayHello() {
        return "Hello";
    }
      
    public String sayWorld() {
        return "World";
    }
}
Copy after login
Copy after login

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;
    }
    
}
Copy after login
//客户端调用
TargetInterface target = new ClassAdapter();
ClientInvoking.invoke(target);
Copy after login

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;
    }
    
}
Copy after login
//客户端调用
TargetInterface target = new ClassAdapter(new ExistClass());
ClientInvoking.invoke(target);
Copy after login

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);
    }

}
Copy after login

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";
    }

}
Copy after login
//已有类及方法
public class ExistClass {

    public String sayHello() {
        return "Hello";
    }
      
    public String sayWorld() {
        return "World";
    }
}
Copy after login
Copy after login

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;
    }
    
}
Copy after login
//客户端调用
TargetClass target = new ClassAdapter(new ExistClass());
ClientInvoking.invoke(target);
Copy after login

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);
    ...
}
Copy after login
//添加监听器的例子
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) {

    }
    ...
})
Copy after login

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) {}
    ...
}
Copy after login
//重写方法
public class OverrideWindowClosing extends ListenerAdapter {
    
    @Override    
    public void windowClosing(WindowEvent e) {        
       //TODO    
    }
    
}
Copy after login
//客户端调用
frame.addWindowListener(new OverrideWindowClosing());
Copy after login

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Java Spring Interview Questions Java Spring Interview Questions Aug 30, 2024 pm 04:29 PM

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP vs. Python: Core Features and Functionality PHP vs. Python: Core Features and Functionality Apr 13, 2025 am 12:16 AM

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

Create the Future: Java Programming for Absolute Beginners Create the Future: Java Programming for Absolute Beginners Oct 13, 2024 pm 01:32 PM

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.

See all articles