Home Java javaTutorial Illustration of Adapter Pattern in Java Design Patterns

Illustration of Adapter Pattern in Java Design Patterns

Oct 18, 2017 am 09:36 AM
java Design Patterns adapter

This article mainly introduces the adapter pattern notes of Java design pattern in detail, which has certain reference value. Interested friends can refer to

Adapter pattern:

The adapter pattern transforms the interface of a class into another interface expected by the client, so that two classes that were originally unable to work together due to mismatched interfaces can work together.

Scenes in life:

1. Laptop power adapter can convert 220v into a voltage suitable for laptop use.

2. Insert the keyboard of the desktop PS/2 interface into the USB interface of the laptop. A USB and PS/2 interface adapter is required. At this time, the USB and PS/2 interface adapter is required. It acts as an adapter.

Illustration of Adapter Pattern in Java Design Patterns

General class diagram:

Illustration of Adapter Pattern in Java Design Patterns

In the above general class diagram, the Cient class What we end up facing is the Target interface (or abstract class), which can only use subclasses that meet this target standard; and the Adaptee class is the adapted object (also called the source role) because it contains specific (special ) operations, functions, etc., so we want to use it in our own system and convert it into a class that meets our standards, so that the Client class can choose to use the ConcreteTarget class or the Adaptee class with special functions in a transparent manner. .

Roles in the adapter pattern:

Target 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): interface or adaptation class that needs to be adapted.
Adapter: The adapter class is the core of this pattern. The adapter converts the source interface into the target interface by wrapping an object that needs to be adapted. Obviously, this role cannot be an interface, but must be a concrete class.

The structure of the adapter pattern:

The adapter pattern has two different forms: class adapter pattern and object adapter pattern.

The adapter pattern of a class converts the API of the adapted class into the API of the target class.

The object adapter pattern is the same as the class adapter pattern. The object adapter pattern converts the API of the adapted class into the API of the target class. Unlike the class adapter pattern, the object adapter pattern is not Use an inheritance relationship to connect to the Adaptee class, but use a delegation relationship to connect to the Adaptee class.

Class adapter pattern

1. Create an adapted class:


/**
 * 被适配的类
 * 已存在的、具有特殊功能、但不符合我们既有的标准接口的类
 * (相当于例子中的,PS/2键盘)
 * @author ChuanChen
 * 
 */
public class Adaptee {

  public void specificRequest(){
    System.out.println("可以完成客户请求的需要的功能!");
  }
}
Copy after login
Copy after login

2. Create a target interface that can handle some special requests


/**
 * 目标接口,或称为标准接口
 * @author ChuanChen
 *
 */
public interface Target {
  void handleReq();
}
Copy after login
Copy after login

3. Create an adapter (class adapter method)


/**
 * 适配器 (类适配器方式)
 * (相当于usb和ps/2的转接器)
 * @author ChuanChen
 *
 */
public class Adapter extends Adaptee implements Target {


  @Override
  public void handleReq() {
    super.specificRequest();
  }
}
Copy after login

4. Create a client


/**
 * 客户端类
 * (相当于例子中的笔记本,只有USB接口)
 * @author ChuanChen
 *
 */
public class Client {

  public void test(Target t){
    t.handleReq();
  }

  public static void main(String[] args) {
    Client c = new Client();
    Adaptee a = new Adaptee();
    Target t = new Adapter();
    c.test(t); 
  }  
}
Copy after login

The adapter implemented above is called a class adapter, because the Adapter class not only inherits Adaptee (the adapted class), but also The Target interface is implemented (because Java does not support multiple inheritance, so it is implemented this way). In the Client class, we can choose and create any subclass that meets the needs as needed to implement specific functions.

Adapter pattern of objects

1. Create an adapted class:


/**
 * 被适配的类
 * 已存在的、具有特殊功能、但不符合我们既有的标准接口的类
 * (相当于例子中的,PS/2键盘)
 * @author ChuanChen
 * 
 */
public class Adaptee {

  public void specificRequest(){
    System.out.println("可以完成客户请求的需要的功能!");
  }
}
Copy after login
Copy after login

2. Create a target interface that can Handle some special requests


/**
 * 目标接口,或称为标准接口
 * @author ChuanChen
 *
 */
public interface Target {
  void handleReq();
}
Copy after login
Copy after login

3. Create an adapter (object adapter method, using a combination method to integrate with the adapted object)


/**
 * 适配器 (对象适配器方式,使用了组合的方式跟被适配对象整合)
 * (相当于usb和ps/2的转接器)
 * @author ChuanChen
 *
 */

public class Adapter implements Target{

private Adaptee adaptee;

  @Override
  public void handleReq() {
    adaptee.specificRequest();
  }

  public Adapter(Adaptee adaptee) {
    super();
    this.adaptee = adaptee;
  }

}
Copy after login

4. Create a client


/**
 * 客户端类
 * (相当于例子中的笔记本,只有USB接口)
 * @author ChuanChen
 *
 */
public class Client {

  public void test(Target t){
    t.handleReq();
  }

  public static void main(String[] args) {
    Client c = new Client();
    Adaptee a = new Adaptee();
    Target t = new Adapter(a);
    c.test(t);
  }  
}
Copy after login

We only need to modify the internal structure of the Adapter class, that is, the Adapter itself must first have an adapted Class object, and then delegate specific special functions to this object to implement. 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.

The trade-off between class adapter and object adapter:

  • Class adapter uses object inheritance, which is a static definition method; while object adapter uses The way objects are combined is dynamic combination.

  • For class adapters, since the adapter directly inherits Adaptee, the adapter cannot work with subclasses of Adaptee, because inheritance is a static relationship. When the adapter inherits Adaptee, it will not Maybe we'll deal with subclasses of Adaptee again.

  • For object adapters, an adapter can adapt multiple different sources to the same target. In other words, the same adapter can adapt both the source class and its subclasses to the target interface. Because the object adapter uses the relationship of object combination, as long as the object type is correct, it does not matter whether it is a subclass or not.

  • For class adapters, the adapter can redefine part of the behavior of Adaptee, which is equivalent to the subclass overriding some implementation methods of the parent class.

  • For object adapters, it is difficult to redefine the behavior of Adaptee. In this case, you need to define a subclass of Adaptee to achieve the redefinition, and then let the adapter combine the subclasses. Although it is difficult to redefine the behavior of Adaptee, it is very convenient to add some new behaviors, and the newly added behaviors can be applied to all sources at the same time.

  • For class adapters, only one object is introduced, and no additional references are needed to indirectly obtain the Adaptee.

  • For object adapters, additional references are needed to indirectly obtain Adaptee.

It is recommended to use object adapter implementation as much as possible, using more synthesis/aggregation and less use of inheritance. Of course, specific problems should be analyzed in detail, and the implementation method should be selected according to needs. The most suitable one is the best.

Advantages of the adapter pattern:

Better reusability:

The system needs to use existing classes, but the interface of this class does not meet the needs of the system. Then these functions can be better reused through the adapter mode.

Better scalability:

When implementing the adapter function, you can call the functions you developed yourself, This naturally expands the functionality of the system.
Disadvantages of the adapter mode

Excessive use of adapters will make the system very messy and difficult to grasp as a whole. For example, it is obvious that interface A is being called, but in fact it is internally adapted to implement interface B. If this happens too much in a system, it will be tantamount to a disaster. Therefore, if it is not necessary, you can reconstruct the system directly without using the adapter.

Scenes of the adapter mode at work:

1. The interface of the existing class does not meet our needs;
2. Create a reusable class so that the class can work together with other unrelated classes or unforeseen classes (that is, classes whose interfaces may not necessarily be compatible);
3. Without subclassing each one to match their In the case of interfaces, use some existing subclass.

The adapter mode is often used for retrofitting and upgrading old systems. If our system never needs maintenance after development, then many patterns are unnecessary. But unfortunately, in fact, the cost of maintaining a system is often several times that of developing one.

The above is the detailed content of Illustration of Adapter Pattern in Java Design Patterns. 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 Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

Hot Topics

Java Tutorial
1666
14
PHP Tutorial
1273
29
C# Tutorial
1253
24
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.

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.

PHP's Impact: Web Development and Beyond PHP's Impact: Web Development and Beyond Apr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

PHP: The Foundation of Many Websites PHP: The Foundation of Many Websites Apr 13, 2025 am 12:07 AM

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.

PHP vs. Python: Use Cases and Applications PHP vs. Python: Use Cases and Applications Apr 17, 2025 am 12:23 AM

PHP is suitable for web development and content management systems, and Python is suitable for data science, machine learning and automation scripts. 1.PHP performs well in building fast and scalable websites and applications and is commonly used in CMS such as WordPress. 2. Python has performed outstandingly in the fields of data science and machine learning, with rich libraries such as NumPy and TensorFlow.

See all articles