假设有一个电商网站,提供了多种支付方式,如支付宝、微信支付、银联支付等。这些支付方式的接口不尽相同,但是我们希望在调用时能够使用相同的接口,这时候就可以使用适配器模式。
首先定义一个支付接口 Payment:
public interface Payment {
void pay(String orderId, double amount);
}
然后定义三个具体的支付方式,它们的接口不尽相同:
public class Alipay {
public void doPay(String orderId, double amount) {
System.out.println("Alipay do pay: " + orderId + ", " + amount);
}
}
public class WechatPay {
public void makePayment(String orderId, double amount) {
System.out.println("Wechat pay: " + orderId + ", " + amount);
}
}
public class UnionPay {
public void payMoney(double amount, String orderId) {
System.out.println("Union pay: " + orderId + ", " + amount);
}
}
接着,我们定义适配器类,将三个具体的支付方式适配到 Payment 接口:
public class PaymentAdapter implements Payment {
private Alipay alipay;
private WechatPay wechatPay;
private UnionPay unionPay;
public PaymentAdapter(Alipay alipay, WechatPay wechatPay, UnionPay unionPay) {
this.alipay = alipay;
this.wechatPay = wechatPay;
this.unionPay = unionPay;
}
@Override
public void pay(String orderId, double amount) {
if (alipay != null) {
alipay.doPay(orderId, amount);
} else if (wechatPay != null) {
wechatPay.makePayment(orderId, amount);
} else if (unionPay != null) {
unionPay.payMoney(amount, orderId);
}
}
}
最后,在客户端代码中调用支付接口,使用适配器类实现支付功能:
public class Client {
public static void main(String[] args) {
Alipay alipay = new Alipay();
WechatPay wechatPay = new WechatPay();
UnionPay unionPay = new UnionPay();
Payment payment = new PaymentAdapter(alipay, wechatPay, unionPay);
payment.pay("1001", 100.0);
}
}
在上面的代码中,我们通过适配器类将三个具体的支付方式适配到 Payment 接口,从而实现了相同的支付接口。在客户端代码中,我们只需要调用 Payment 接口的 pay 方法,无需关心具体的支付方式。