directory

  • What is the adapter pattern?
  • The mission of the adapter pattern?
  • The concrete implementations of the adapter pattern are class adapters and object adapters

What is the adapter pattern?

The adapter pattern is a design pattern that translates the interface of one class into another interface that the customer wants.

The mission of the adapter pattern?

The adapter pattern was born to solve the problem of incompatibilities between objects that need to cooperate. An adapter is used to bridge the cooperation between two incompatible objects, and the two incompatible objects cooperate through the adapter without direct contact. The adapter pattern addresses the following issues:

  1. The system needs to use an existing class that does not meet the system’s needs, that is, the interface is incompatible.
  2. You need to build a reusable class to work with classes that don’t have much to do with each other.
  3. A unified output interface is required, but the output short type is unpredictable.

A concrete implementation of the adapter pattern

There are two types of adapter patterns, class adapters and object adapters. The adaptor mode can be used in the following scenarios: the laptop power supply voltage is 5V, and the life wire voltage is 220. Now you need the adapter mode to enable the laptop to use the power supply from the living wire.

The class adapter

The implementation of the class adapter uses an inheritance mechanism in which the adapter inherits the interfaces of both objects.

public interface Laptop {

    int getVolt5(a);
}

public class PowerSupply {

    public int getVolt220(a) {
        return 220; }}public class VoltAdapter extends PowerSupply implements Laptop {
    @Override
    public int getVolt5(a) {
        return getVolt220() / 44; }}public class VoltAdapterTest {

    @Test
    public void voltTest(a) {
        VoltAdapter voltAdapter = new VoltAdapter();
        System.out.println("Output voltage:"+ voltAdapter.getVolt5()); Output voltage:5

Copy the code

Object adapter

Object adapters are implemented using the principle of composition: the adapter implements the interface of one object and encapsulates the other.

public interface Laptop {

    int getVolt5(a);
}

public class PowerSupply {

    public int getVolt220(a) {
        return 220; }}public class VoltAdapter extends PowerSupply implements Laptop {

    private PowerSupply mPowerSupply;

    public VoltAdapter(PowerSupply powerSupply) {
        mPowerSupply = powerSupply;
    }

    @Override
    public int getVolt5(a) {
        return mPowerSupply.getVolt220() / 44; }}public class VoltAdapterTest {

    @Test
    public void voltTest(a) {
        VoltAdapter voltAdapter = new VoltAdapter();
        System.out.println("Output voltage:"+ voltAdapter.getVolt5()); Output voltage:5
Copy the code