java设计模式-策略设计模式

  • 为什么要使用设计模式
  1. 重构代码
  2. 提高代码的复用性、跨站性、减少代码冗余量
  • 设计模式的六大原则
  1. 开闭原则
    就是对扩展开放,对修改关闭
    在程序需要进行拓展的时候,不能去修改原有的代码,实现一个热插拔的效果。
    为了使程序的扩展性好,易于维护和升级。想要达到这样的效果,我们需要使用接口和抽象类,后面的具体设计中我们会提到这点。
  2. 里氏代换原则
    面向对象设计的基本原则之一
    任何基类可以出现的地方,子类一定可以出现。
    里氏代换原则是对“开-闭”原则的补充。实现“开-闭”原则的关键步骤就是抽象化。
  3. 依赖倒转
    是开闭原则的基础,具体内容:真对接口编程,依赖于抽象而不依赖于具体
  4. 接口隔离
    使用多个隔离的接口,比使用单个接口要好。还是一个降低类之间的耦合度的意思
    从这儿我们看出,其实设计模式就是一个软件的设计思想,从大型软件架构出发,为了升级和维护方便。所以上文中多次出现:降低依赖,降低耦合。
  5. 迪米特
    也叫"最少知道原则",就是说:一个实体应当尽量少的与其他实体之间发生相互作用,使得系统功能模块相对独立。
  6. 合成复用
    原则是尽量使用合成/聚合的方式,而不是使用继承
  • 设计模式分类
  1. 创建型模式
    工厂方法模式、抽象工厂模式、单例模式、建造者模式、原型模式
  2. 结构性模式
    适配器模式、装饰器模式、代理模式、外观模式、桥接模式、组合模式、享元模式
  3. 行为模式
    策略模式、模板方法模式、观察者模式、迭代子模式、责任链模式、命令模式、备忘录模式
    状态模式、访问者模式、中介者模式、解释器模式
  • 什么是策略模式
  1. 策略模式是对算法的包装,是把使用算法的责任和算法本身分割开来,委派给不同的对象管理,最终可以实现解决多重if判断问题
  2. 策略模式的角色:
    a、环境角色:可以帮助实现获取具体的角色
    b、抽象策略角色:通常是定义一个共同行为的接口、实现类,
    c、具体策略角色:表示接口的不同实现,包装了相关算法和行为
  3. 为什么叫策略模式:每个if判断可以理解为就是一个策略。
  • 策略模式的应用场景
  1. 聚合支付平台项目
  2. 搭建聚合支付平台的时候,这时候需要对接很多第三方支付接口,比如支付宝、微信支付、小米支付等。
    public  String toPay(String code){
        if(code.equals("ali_pay")){
            return  "调用支付宝接口...";
        }
        if(code.equals("xiaomi_pay")){
            return  "调用小米支付接口";
        }
        if(code.equals("yinlian_pay")){
            return  "调用银联支付接口...";
        }
        return  "未找到该接口...";
    }
    

     

  3. 传统if代码判断的,后期的维护性非常差!这时候可以通过策略模式解决多重if判断问题。
  4. 策略模式架构图
  • 具体例子

  1. 创建一个springboot项目
  2. 在pom.xml中引入依赖
    <parent>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>2.1.4.RELEASE</version>
            <relativePath/> <!-- lookup parent from repository -->
        </parent>
    
        <properties>
            <java.version>1.8</java.version>
        </properties>
    
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-test</artifactId>
            </dependency>
            <!-- springboot整合mybatis  引入依赖 -->
            <dependency>
                <groupId>org.mybatis.spring.boot</groupId>
                <artifactId>mybatis-spring-boot-starter</artifactId>
                <version>1.3.0</version>
            </dependency>
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
            </dependency>
            <dependency>
                <groupId>org.projectlombok</groupId>
                <artifactId>lombok</artifactId>
                <version>1.16.20</version>
            </dependency>
        </dependencies>

     

  3. 创建抽象策略PayStrategy.java接口
    /**
     * 抽象策略
     * Create by wangxb
     * 2019-05-11 16:36
     */
    public interface PayStrategy {
        /**
         * 共同方法行为
         * @return
         */
        String toPayHtml();
    }

     

  4. 创建具体策略实现AliPayStrategy.java , WeixinPayStrategy.java
    import com.basic.strategy.PayStrategy;
    import org.springframework.stereotype.Component;
    
    /**
     * 具体策略的实现
     * Create by wangxb
     * 2019-05-11 16:36
     */
    @Component
    public class AliPayStrategy implements PayStrategy {
        @Override
        public String toPayHtml() {
            return "调用支付宝接口......";
        }
    }
    
    
    /**
     * 具体策略的实现
     * Create by wangxb
     * 2019-05-11 16:36
     */
    @Component
    public class WeixinPayStrategy implements PayStrategy {
        @Override
        public String toPayHtml() {
            return "调用微信接口......";
        }
    }

     

  5. 创建实体类PaymentChannelEntity.java
    /**
     * Create by wangxb
     * 2019-05-12 7:17
     */
    public class PaymentChannelEntity {
    
        /** ID */
        private Integer id;
        /** 渠道名称 */
        private String channelName;
        /** 渠道ID */
        private String channelId;
        /**
         * 策略执行beanId
         */
        private String strategyBeanId;
    
        public Integer getId() {
            return id;
        }
    
        public void setId(Integer id) {
            this.id = id;
        }
    
        public String getChannelName() {
            return channelName;
        }
    
        public void setChannelName(String channelName) {
            this.channelName = channelName;
        }
    
        public String getChannelId() {
            return channelId;
        }
    
        public void setChannelId(String channelId) {
            this.channelId = channelId;
        }
    
        public String getStrategyBeanId() {
            return strategyBeanId;
        }
    
        public void setStrategyBeanId(String strategyBeanId) {
            this.strategyBeanId = strategyBeanId;
        }
    }

     

  6. 创建PaymentChannelMapper.java
    import com.basic.strategy.entity.PaymentChannelEntity;
    import org.apache.ibatis.annotations.Mapper;
    import org.apache.ibatis.annotations.Select;
    
    /**
     * Create by wangxb
     * 2019-05-12 7:22
     */
    @Mapper
    public interface PaymentChannelMapper {
    
        @Select("\n" +
                "SELECT  id as id ,CHANNEL_NAME as CHANNELNAME ,CHANNEL_ID as CHANNELID,strategy_bean_id AS strategybeanid\n" +
                "FROM payment_channel where CHANNEL_ID=#{code}")
        public PaymentChannelEntity getPaymentChannel(String code);
    
    }
     
     
  7. 常见SpringUtils.java
    import org.springframework.beans.BeansException;
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.ApplicationContextAware;
    import org.springframework.stereotype.Component;
    
    /**
     * Create by wangxb
     * 2019-05-12 7:25
     */
    @Component
    public class SpringUtils implements ApplicationContextAware {
    
        private static ApplicationContext applicationContext;
    
        @Override
        public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
            this.applicationContext = applicationContext;
        }
    
        //获取applicationContext
        public static ApplicationContext getApplicationContext() {
            return applicationContext;
        }
    
        //通过name获取 Bean.
        public static Object getBean(String name){
            return getApplicationContext().getBean(name);
        }
    
        //通过class获取Bean.
        public static <T> T getBean(Class<T> clazz){
            return getApplicationContext().getBean(clazz);
        }
    
        //通过name,以及Clazz返回指定的Bean
        public static <T> T getBean(String name,Class<T> clazz){
            return getApplicationContext().getBean(name, clazz);
        }
    
    }

     

  8. 创建策略上下文
    import com.basic.strategy.PayStrategy;
    import com.basic.strategy.entity.PaymentChannelEntity;
    import com.basic.strategy.mapper.PaymentChannelMapper;
    import com.basic.strategy.utils.SpringUtils;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Component;
    import org.springframework.util.StringUtils;
    
    /**
     * 策略上下文
     * Create by wangxb
     * 2019-05-11 22:05
     */
    @Component
    public class PayContextStrategy {
    
        @Autowired
        private PaymentChannelMapper paymentChannelMapper;
    
        // 获取策略的具体实现
        public String toPayHtml(String code){
            // 1.验证参数
            if(StringUtils.isEmpty(code)){
                return  "payCode不能为空!";
            }
            // 2.使用PayCode查询
            PaymentChannelEntity paymentChannel = paymentChannelMapper.getPaymentChannel(code);
            if(paymentChannel==null){
                return  "该渠道为空...";
            }
            // 3.获取策略执行的beanid
            String strategyBeanId = paymentChannel.getStrategyBeanId();
            // 4.使用strategyBeanId获取对应spring容器bean信息
            PayStrategy payStrategy = SpringUtils.getBean(strategyBeanId, PayStrategy.class);
            // 5.执行具体策略算法
            return  payStrategy.toPayHtml();
        }
    
    
    }
  9. 配置appliction.yml
    ###服务启动端口号
    server:
      port: 8080
    spring:
    ###数据库相关连接      
      datasource:
        username: root
        password: 123456
        driver-class-name: com.mysql.jdbc.Driver
        url: jdbc:mysql://127.0.0.1:3306/basic?useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2B8

     

  10. 数据库的建表语句
    DROP TABLE IF EXISTS `payment_channel`;
    CREATE TABLE `payment_channel` (
      `ID` int(11) NOT NULL AUTO_INCREMENT COMMENT 'ID',
      `CHANNEL_NAME` varchar(32) NOT NULL COMMENT '渠道名称',
      `CHANNEL_ID` varchar(32) NOT NULL COMMENT '渠道ID',
      `strategy_bean_id` varchar(255) DEFAULT NULL COMMENT '策略执行beanid',
      PRIMARY KEY (`ID`,`CHANNEL_ID`)
    ) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8 COMMENT='支付渠道 ';
    
    -- ----------------------------
    -- Records of payment_channel
    -- ----------------------------
    INSERT INTO `payment_channel` VALUES ('4', '支付宝渠道', 'ali_pay', 'aliPayStrategy');
    INSERT INTO `payment_channel` VALUES ('5', '小米支付渠道', 'xiaomi_pay', 'xiaoMiPayStrategy');
    

     

  11. 创建一个controller测试
    import com.basic.strategy.context.PayContextStrategy;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RequestParam;
    import org.springframework.web.bind.annotation.RestController;
    
    /**
     * Create by wangxb
     * 2019-05-11 22:58
     */
    @RestController
    public class IndexController {
    
        @Autowired
        private PayContextStrategy payContextStrategy;
        @GetMapping("/index")
        public String index(@RequestParam("code") String code){
            return payContextStrategy.toPayHtml(code);
        }
    }

     

  12. 启动项目
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    
    @SpringBootApplication
    public class StrategyApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(StrategyApplication.class, args);
        }
    
    }

     

  13. 测试http://localhost:8080/index?code=ali_pay_strategy
  • 策略模式的优缺点
  1. 优点 
    策略模式最终帮助我们解决在实际开发中多重if判断问题、提高扩展性、维护性增强、提高代码可读性。
  2. 缺点..

    后期维护不同策略类是非常多、定义类比较多、代码量增大。优点大于缺点。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值