search
HomeJavajavaTutorialAnalysis of Java Design Patterns: How to Implement the Adapter Pattern

Analysis of Java Design Patterns: How to Implement the Adapter Pattern


1. What is the adapter pattern:

The adapter pattern is mainly used to convert the interface of a class into what the client wants. The target class format allows originally incompatible classes to work together, decoupling the target class and the adapter class; it also conforms to the "opening and closing principle", and new adapter classes can be added without modifying the original code; Encapsulating the specific implementation in the adapter class is transparent to the client class and improves the reusability of the adapter. However, the disadvantage is that the implementation process of replacing the adapter is relatively complicated.

So, the adapter mode is more suitable for the following scenarios:

  • (1) The system needs to use existing classes, and the interfaces of these classes do not conform to the system interfaces.

  • (2) When using a third-party component, the component interface definition is different from your own definition. You do not want to modify your own interface, but you must use the functions of the third-party component interface.

The following two very vivid examples illustrate well what the adapter pattern is:

Analysis of Java Design Patterns: How to Implement the Adapter Pattern

Analysis of Java Design Patterns: How to Implement the Adapter Pattern

2. Three ways to implement the adapter pattern:

The adapter pattern is mainly divided into three categories: class adapter pattern, object adapter pattern, and interface adapter pattern.

1. Class adapter pattern:

Analysis of Java Design Patterns: How to Implement the Adapter Pattern

  • ##Goal Interface (Target): The interface that customers expect. The target can be a concrete or abstract class, or an interface.

  • Class that needs to be adapted (Adaptee): The class that needs to be adapted or the adapter class.

  • Adapter: Converts the original interface into the target interface by packaging an object that needs to be adapted.

// 已存在的、具有特殊功能、但不符合我们既有的标准接口的类
class Adaptee {
	public void specificRequest() {
		System.out.println("被适配类具有 特殊功能...");
	}
}
 
// 目标接口,或称为标准接口
interface Target {
	public void request();
}
 
// 具体目标类,只提供普通功能
class ConcreteTarget implements Target {
	public void request() {
		System.out.println("普通类 具有 普通功能...");
	}
}
 
// 适配器类,继承了被适配类,同时实现标准接口
class Adapter extends Adaptee implements Target{
	public void request() {
		super.specificRequest();
	}
}
 
// 测试类public class Client {
	public static void main(String[] args) {
		// 使用普通功能类
		Target concreteTarget = new ConcreteTarget();
		concreteTarget.request();
		
		// 使用特殊功能类,即适配类
		Target adapter = new Adapter();
		adapter.request();
	}
}
Run result:

普通类 具有 普通功能...
被适配类具有 特殊功能...

2. Object adapter mode:

Analysis of Java Design Patterns: How to Implement the Adapter Pattern

// 适配器类,直接关联被适配类,同时实现标准接口
class Adapter implements Target{
	// 直接关联被适配类
	private Adaptee adaptee;
	
	// 可以通过构造函数传入具体需要适配的被适配类对象
	public Adapter (Adaptee adaptee) {
		this.adaptee = adaptee;
	}
	
	public void request() {
		// 这里是使用委托的方式完成特殊功能
		this.adaptee.specificRequest();
	}
}
 
// 测试类
public class Client {
	public static void main(String[] args) {
		// 使用普通功能类
		Target concreteTarget = new ConcreteTarget();
		concreteTarget.request();
		
		// 使用特殊功能类,即适配类,
		// 需要先创建一个被适配类的对象作为参数
		Target adapter = new Adapter(new Adaptee());
		adapter.request();
	}
}

The test results are consistent with the above. From the class diagram, we also know that what needs to be modified is just the internal structure of the Adapter class, that is, the Adapter itself must first have an object of the adapted class, and then delegate specific special functions to this object for implementation. Using the object adapter mode, the Adapter class (adaptation class) can adapt to multiple different adapted classes based on the incoming Adaptee object. Of course, at this time we can extract an interface for multiple adapted classes. or abstract class. It seems that the object adapter pattern is more flexible.

3. Adapter mode of interface:

Sometimes there are multiple abstract methods in an interface we write. When we write the implementation class of the interface, they must be implemented All methods of this interface, which is obviously sometimes wasteful, because not all methods are what we need, sometimes only some are needed. In order to solve this problem, we introduce the adapter mode of the interface, with the help of an abstract class , this abstract class implements the interface and all methods, and we do not deal with the original interface, only get in touch with the abstract class, so we write a class, inherit the abstract class, and rewrite the methods we need. . Take a look at the class diagram:

Analysis of Java Design Patterns: How to Implement the Adapter Pattern

This is easy to understand. In actual development, we often encounter too many methods defined in this interface, so that sometimes we Not all are required in some implementation classes. Look at the code:

public interface Sourceable {
	
	public void method1();
	public void method2();
}

Abstract class Wrapper2:

public abstract class Wrapper2 implements Sourceable{
	
	public void method1(){}
	public void method2(){}
}

public class SourceSub1 extends Wrapper2 {
	public void method1(){
		System.out.println("the sourceable interface's first Sub1!");
	}
}

public class SourceSub2 extends Wrapper2 {
	public void method1(){
		System.out.println("the sourceable interface's second Sub2!");
	}
}
public class WrapperTest {
 
	public static void main(String[] args) {
		Sourceable source1 = new SourceSub1();
		Sourceable source2 = new SourceSub2();
		
		source1.method1();
		source1.method2();
		source2.method1();
		source2.method2();
	}
}

Running results:

the sourceable interface's first Sub1!
the sourceable interface's second Sub2!

The above is the detailed content of Analysis of Java Design Patterns: How to Implement the Adapter Pattern. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?Mar 17, 2025 pm 05:46 PM

The article discusses using Maven and Gradle for Java project management, build automation, and dependency resolution, comparing their approaches and optimization strategies.

How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?Mar 17, 2025 pm 05:45 PM

The article discusses creating and using custom Java libraries (JAR files) with proper versioning and dependency management, using tools like Maven and Gradle.

How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?Mar 17, 2025 pm 05:44 PM

The article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra

How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?Mar 17, 2025 pm 05:43 PM

The article discusses using JPA for object-relational mapping with advanced features like caching and lazy loading. It covers setup, entity mapping, and best practices for optimizing performance while highlighting potential pitfalls.[159 characters]

How does Java's classloading mechanism work, including different classloaders and their delegation models?How does Java's classloading mechanism work, including different classloaders and their delegation models?Mar 17, 2025 pm 05:35 PM

Java's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

DVWA

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

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),