1.声明支付接口
public interface PaymentService { void pay(String orderId); }
2.定义支付宝实现类
public class Alipay implements PaymentService{ @Override public void pay(String orderId) { System.out.println("支付宝支付:订单支付"+orderId+"成功"); } }
3.定义微信支付实现类
public class WeChat implements PaymentService{ @Override public void pay(String orderId) { System.out.println("微信支付:订单支付"+orderId+"成功"); } }
4.银联支付
public class UnionPay { void PayWithUnionPay(String orderId){ System.out.println("银联支付:订单支付"+orderId+"成功"); } }
5.适配器类(银联支付的适配器)
public class UnionPayAdapter implements PaymentService{ private UnionPay unionPay; @Override public void pay(String orderId) { System.out.println("适配器:使用银联支付的适配器..."); unionPay.PayWithUnionPay(orderId); } public UnionPayAdapter(UnionPay unionPay) { this.unionPay = unionPay; } }
6.支付服务工厂类
public class PayFactory { public static PaymentService createPay(String type){ if (type.equalsIgnoreCase("Ali")){ return new Alipay(); }else if (type.equalsIgnoreCase("WeChat")){ return new WeChat(); }else if (type.equalsIgnoreCase("Union")){ UnionPay unionPay = new UnionPay(); return new UnionPayAdapter(unionPay); }else { return null; } } }
7.测试
public class test03 { public static void main(String[] args) { PaymentService ali = PayFactory.createPay("Ali"); PaymentService weChat = PayFactory.createPay("WeChat"); PaymentService union = PayFactory.createPay("Union"); ali.pay("101"); weChat.pay("102"); union.pay("103"); } }