天津市建设工程网站,网络推广方法怎么做,wordpress百度索引链接,仿58同城网站模板适配器模式将一个类的接口转换成客户端所期望的另一个接口#xff0c;解决由于接口不兼容而无法进行合作的问题。
设计基本步骤
1. 创建目标接口#xff08;Target Interface#xff09;#xff0c;该接口定义了客户端所期望的方法。
2.创建被适配类#xff08;Adaptee…适配器模式将一个类的接口转换成客户端所期望的另一个接口解决由于接口不兼容而无法进行合作的问题。
设计基本步骤
1. 创建目标接口Target Interface该接口定义了客户端所期望的方法。
2.创建被适配类Adaptee Class该类是需要被适配的类它包含了一些已经存在的方法。
3. 创建适配器类Adapter Class该类实现了目标接口并包含被适配对象的引用。
4. 在适配器类中实现目标接口的方法并在方法内部调用被适配类的方法。 实例介绍运用
假设我们正在开发一个电子支付业务该系统需要与不同的支付服务提供商进行集成支付宝、微信支付和银联支付每个支付服务提供商都有自己的接口和方法来处理支付请求我们希望将支付服务提供商的接口适配成了统一的支付接口转换我们可以使用适配器模式实现这样三种支付方式我们都能同时处理。
1. 创建目标接口
public interface PaymentService {void pay(String paymentType, double amount);
}
2.创建被适配类
public class AlipayService implements PaymentService {//支付宝支付Overridepublic void pay(String paymentType, double amount) {System.out.println(Alipay payment: amount CNY);}
}public class WechatPayService implements PaymentService {//微信支付Overridepublic void pay(String paymentType, double amount) {System.out.println(WeChat payment: amount CNY);}
}public class UnionPayService implements PaymentService {//银联支付Overridepublic void pay(String paymentType, double amount) {System.out.println(UnionPay payment: amount CNY);}
}
3. 创建适配器类、实现方法
public class PaymentAdapter implements PaymentService {//被适配对象引用private AlipayService alipayService;private WechatPayService wechatPayService;private UnionPayService unionPayService;//初始化public PaymentAdapter() {alipayService new AlipayService();wechatPayService new WechatPayService();unionPayService new UnionPayService();}Overridepublic void pay(String paymentType, double amount) {//实现统一支付逻辑if (paymentType.equalsIgnoreCase(Alipay)) {alipayService.pay(paymentType, amount);} else if (paymentType.equalsIgnoreCase(WeChatPay)) {wechatPayService.pay(paymentType, amount);} else if (paymentType.equalsIgnoreCase(UnionPay)) {unionPayService.pay(paymentType, amount);} else {//其他方式不支持System.out.println(Unsupported payment type: paymentType);}}
}
4.客户端简单实现
public class Main {public static void main(String[] args) {PaymentService paymentService new PaymentAdapter();paymentService.pay(Alipay, 10000.0);paymentService.pay(WeChatPay, 20000.0);paymentService.pay(UnionPay, 30000.0);paymentService.pay(ApplePay, 500.0);}
}