设计模式之适配者模式

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");

    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值