• 【设计模式】策略模式


    策略模式

    1.什么是策略模式

    • 定义了一系列的算法 或 逻辑 或 相同意义的操作,并将每一个算法、逻辑、操作封装起来,而且使它们还可以相互替换。(其实策略模式Java中用的非常非常广泛)

    • 我觉得主要是为了 简化 if…else 所带来的复杂和难以维护。

    2.策略模式应用场景

    • 策略模式的用意是针对一组算法或逻辑,将每一个算法或逻辑封装到具有共同接口的独立的类中,从而使得它们之间可以相互替换。
    1. 例如:我要做一个不同会员打折力度不同的三种策略,初级会员,中级会员,高级会员(三种不同的计算)。

    2. 例如:我要一个支付模块,我要有微信支付、支付宝支付、银联支付等

    3.策略模式的优点和缺点

    • 优点: 1、算法可以自由切换。 2、避免使用多重条件判断。 3、扩展性非常良好。

    • 缺点: 1、策略类会增多。 2、所有策略类都需要对外暴露。

    4.代码演示

    模拟支付模块有微信支付、支付宝支付、银联支付

    1. 定义抽象的公共方法
    package com.lijie;
    
    //策略模式 定义抽象方法 所有支持公共接口
    abstract class PayStrategy {
    
    	// 支付逻辑方法
    	abstract void algorithmInterface();
    
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    1. 定义实现微信支付
    package com.lijie;
    
    class PayStrategyA extends PayStrategy {
    
    	void algorithmInterface() {
    		System.out.println("微信支付");
    	}
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    1. 定义实现支付宝支付
    package com.lijie;
    
    class PayStrategyB extends PayStrategy {
    
    	void algorithmInterface() {
    		System.out.println("支付宝支付");
    	}
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    1. 定义实现银联支付
    package com.lijie;
    
    class PayStrategyC extends PayStrategy {
    
    	void algorithmInterface() {
    		System.out.println("银联支付");
    	}
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    1. 定义上下文维护算法策略
    package com.lijie;// 使用上下文维护算法策略
    
    class Context {
    
    	PayStrategy strategy;
    
    	public Context(PayStrategy strategy) {
    		this.strategy = strategy;
    	}
    
    	public void algorithmInterface() {
    		strategy.algorithmInterface();
    	}
    
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    1. 运行测试
    package com.lijie;
    
    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();
    		//使用支付逻辑C
    		context = new Context(new PayStrategyC());
    		context.algorithmInterface();
    	}
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
  • 相关阅读:
    cocotb教程(一)
    浅谈高速公路服务区分布式光伏并网发电
    linux系统输入法怎么切换
    机器学习笔记 - 时间序列的趋势分量
    【Linux】网络基础--网络层与数据链路层
    JVM运行时数据区-虚拟机栈
    Visual Studio 2019下编译OpenCV 4.7 与OpenCV 4.7 contrib
    UG\NX二次开发 仿射变换(未缩放向量与缩放向量相加) UF_VEC2_affine_comb
    (个人杂记)第十四章 PWM输出实验
    自研地面站!自主开源无人飞行系统 Prometheus V2 版重大升级详解
  • 原文地址:https://blog.csdn.net/df007df/article/details/133991379