适配器模式

适配器模式是一种结构型设计模式, 它能使接口不兼容的对象能够相互合作。

参考:适配器模式

以下参考了狂神B站视频

1. 继承方式(类适配器)

/**
 * @description: 网线,模拟要被适配的类
 * @author: anyue.long
 * @date: 2022/4/23 10:15
 */
public class NetworkCable {
    public void request() {
        System.out.println("我是网线,用来连接上网的");
    }
}
/**
 * @description: 转接头,模拟适配器的抽象实现,定义成接口
 * @author: anyue.long
 * @date: 2022/4/23 10:22
 */
public interface IAdapter {
    // 处理请求
    void handlerRequest();
}
/**
 * @description: 模拟具体的适配器,需要继承被适配类,实现适配器接口
 * @author: anyue.long
 * @date: 2022/4/23 10:26
 */
public class NetworkAdapter extends NetworkCable implements IAdapter{

    @Override
    public void handlerRequest() {
        super.request();
    }
}
/**
 * @description: 电脑,模拟目标类,需要用到被适配类
 * @author: anyue.long
 * @date: 2022/4/23 10:19
 */
public class Computer {
	// 上网,通过转接头连接上网线,即通过适配器来使用被适配类的方法
    public void netPlay(IAdapter networkAdapter) {
        networkAdapter.handlerRequest();
    }
}
/**
 * @description: 模拟客户端
 * @author: anyue.long
 * @date: 2022/4/23 10:36
 */
public class Client {
    public static void main(String[] args) {
        Computer computer = new Computer();
        NetworkAdapter networkAdapter = new NetworkAdapter();
        computer.netPlay(networkAdapter);
    }
}

2. 组合方式(对象适配器)

/**
 * @description: 模拟具体的适配器,需要继承被适配类,实现适配器接口
 * @author: anyue.long
 * @date: 2022/4/23 10:26
 */
public class NetworkAdapter implements IAdapter {

    private final NetworkCable networkCable;

    public NetworkAdapter(NetworkCable networkCable) {
        this.networkCable = networkCable;
    }

    @Override
    public void handlerRequest() {
        networkCable.request();
    }
}
/**
 * @description: 模拟客户端
 * @author: anyue.long
 * @date: 2022/4/23 10:36
 */
public class Client {
    public static void main(String[] args) {
        Computer computer = new Computer();
        NetworkCable networkCable = new NetworkCable();
        NetworkAdapter networkAdapter = new NetworkAdapter(networkCable);
        computer.netPlay(networkAdapter);
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值