Home  >  Article  >  Java  >  Illustration of Adapter Pattern in Java Design Patterns

Illustration of Adapter Pattern in Java Design Patterns

黄舟
黄舟Original
2017-10-18 09:36:481378browse

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("可以完成客户请求的需要的功能!");
  }
}

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


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

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

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

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("可以完成客户请求的需要的功能!");
  }
}

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


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

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

}

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

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:
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