策略模式应用

文章展示了如何使用Java设计模式中的策略模式来实现不同的支付逻辑,包括微信支付和支付宝支付。通过定义抽象的PayStrategy类,以及其两个具体实现PayStrategyA和PayStrategyB,实现了支付方式的动态切换。Context类作为上下文,负责持有并调用具体的支付策略。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package designMode.celueMode;

//策略模式 定义抽象方法 所有支持公共接口
abstract class PayStrategy {
    // 支付逻辑方法
    abstract void algorithmInterface();
}

package designMode.celueMode;

public class PayStrategyA extends PayStrategy {
    @Override
    void algorithmInterface() {
        System.out.println("微信支付");
    }
}

package designMode.celueMode;

public class PayStrategyB extends PayStrategy {
    @Override
    void algorithmInterface() {
        System.out.println("支付宝支付");
    }
}


package designMode.celueMode;

// 使用上下文维护算法策略
class Context {
    PayStrategy strategy;

    public Context(PayStrategy strategy) {
        this.strategy = strategy;
    }

    public void algorithmInterface() {
        strategy.algorithmInterface();
    }
}


package designMode.celueMode;

public class ClientTestStrategy {
    public static void main(String[] args) {
        Context context;
        //使用支付逻辑A
        context = new Context(new PayStrategyA());
        context.algorithmInterface();
        //使用支付逻辑B
        context = new Context(new PayStrategyB());
        context.algorithmInterface();
    }
}

微信支付
支付宝支付
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值