适配器模式(Adapter mode)

适配器模式

概述

就像电脑和网线之间有时需要一个转接器,不同接口之间有时也需要用转接线相连,已有的部件部件不变,单两者之间有鸿沟,可以在不改变原有结构的基础上,新增一个适配器,即为适配器模式的核心

实践

以下为计算机,网线和转接器的例子
网线类

package com.example.designPattern23.adaptor;

/**
 * 功能描述
 *
 * @since 2022-05-16
 */
public class NetworkCable {
    void request() {
        System.out.println("surfing");
    }
}

转接器接口

package com.example.designPattern23.adaptor;

/**
 * 功能描述
 *
 * @since 2022-05-17
 */
public interface NetToUsb {
    void handleRequest();
}

转接器实现类

package com.example.designPattern23.adaptor;

/**
 * 功能描述
 *
 * @since 2022-05-16
 */
public class Adaptor implements NetToUsb {

    private NetworkCable cable;

    public Adaptor(NetworkCable cable) {
        this.cable = cable;
    }

    @Override
    public void handleRequest() {
        cable.request();
    }
}

电脑类

package com.example.designPattern23.adaptor;

/**
 * 功能描述
 *
 * @since 2022-05-16
 */
public class Computer {
    public void net(NetToUsb adapter) {
        adapter.handleRequest();
    }

    public static void main(String[] args) {
        Computer computer = new Computer();
        NetworkCable networkCable = new NetworkCable();
        Adaptor adaptor = new Adaptor(networkCable);
        computer.net(adaptor);
    }
}
————————

Adapter mode

summary

For example, an adapter is sometimes needed between the computer and the network cable, and different interfaces are sometimes connected with adapter lines. The existing components remain unchanged, but there is a gap between the two. An adapter can be added on the basis of not changing the original structure, which is the core of the adapter model

practice

The following are examples of computers, network cables and adapters
Network cable

package com.example.designPattern23.adaptor;

/**
 * 功能描述
 *
 * @since 2022-05-16
 */
public class NetworkCable {
    void request() {
        System.out.println("surfing");
    }
}

Adapter interface

package com.example.designPattern23.adaptor;

/**
 * 功能描述
 *
 * @since 2022-05-17
 */
public interface NetToUsb {
    void handleRequest();
}

Adapter implementation class

package com.example.designPattern23.adaptor;

/**
 * 功能描述
 *
 * @since 2022-05-16
 */
public class Adaptor implements NetToUsb {

    private NetworkCable cable;

    public Adaptor(NetworkCable cable) {
        this.cable = cable;
    }

    @Override
    public void handleRequest() {
        cable.request();
    }
}

Computer

package com.example.designPattern23.adaptor;

/**
 * 功能描述
 *
 * @since 2022-05-16
 */
public class Computer {
    public void net(NetToUsb adapter) {
        adapter.handleRequest();
    }

    public static void main(String[] args) {
        Computer computer = new Computer();
        NetworkCable networkCable = new NetworkCable();
        Adaptor adaptor = new Adaptor(networkCable);
        computer.net(adaptor);
    }
}