Java 设计模式之适配器模式

Java 设计模式之适配器模式

概述

  • 适配器模式(Adapter):将一个类的接口转换成客户希望的另外一个接口。Adapter模式使得原本由于接口不兼容而不能一起工作的那些类可以一起工作。
  • 适配器模式主要应用于希望复用一些现存的类,但是接口又与复用环境要求不一致的情况。

UML

在这里插入图片描述

  • Target:目标接口,客户期望的接口。
  • Adaptee:适配者类,需要被适配的类。
  • Adapter:适配器类,实现目标接口,负责将Adaptee的接口适配到Target接口。

代码实现

简单实现

定义目标接口:

public interface Target {
    void request();
}

定义适配者类:

public class Adaptee {
    public void specificRequest() {
        System.out.println("特殊请求");
    }
}

定义适配器类:

public class Adapter implements Target {
    private Adaptee adaptee;

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

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

使用:

public class Client {
    public static void main(String[] args) {
        Adaptee adaptee = new Adaptee();
        Adapter adapter = new Adapter(adaptee);
        adapter.request();
    }
}

输出:

特殊请求

复杂实现

定义目标接口:

public interface LoginAdapter {
    /**
     * @param id    标识
     * @param token 凭证
     * @return
     */
    boolean login(String id, String token);
}

定义适配者类:

public class AccountLogin {
    public boolean login(String username, String password) {
        return "admin".equals(username) && "123456".equals(password);
    }
}
public class WeixinLogin {
    public boolean login(String openId) {
        return "wx123456789".equals(openId);
    }
}

定义适配器类:

public class AccountLoginAdapter implements LoginAdapter {
    private AccountLogin accountLogin;

    public AccountLoginAdapter(AccountLogin accountLogin) {
        this.accountLogin = accountLogin;
    }

    @Override
    public boolean login(String id, String token) {
        return accountLogin.login(id, token);
    }
}
public class WeixinLoginAdapter implements LoginAdapter {
    private WeixinLogin weixinLogin;

    public WeixinLoginAdapter(WeixinLogin weixinLogin) {
        this.weixinLogin = weixinLogin;
    }

    @Override
    public boolean login(String id, String token) {
        return weixinLogin.login(id);
    }
}

使用:

public class Client {
    public static void main(String[] args) {
        AccountLogin accountLogin = new AccountLogin();
        LoginAdapter loginService1 = new AccountLoginAdapter(accountLogin);
        boolean result1 = loginService1.login("admin", "123456");
        System.out.println("账号登录结果:" + result1);

        WeixinLogin weixinLogin = new WeixinLogin();
        LoginAdapter loginService2 = new WeixinLoginAdapter(weixinLogin);
        boolean result2 = loginService2.login("wx123456789", null);
        System.out.println("微信登录结果:" + result2);
    }
}

输出:

账号登录结果:true
微信登录结果:true
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值