zoukankan      html  css  js  c++  java
  • 设计模式-行为型模式-策略模式

    策略模式

    在实际工作中我用到了策略模式,但为什么要有环境角色呢?

    这里我贴上英文对含义的介绍,

    The Strategy Pattern defines a family of algorithms,encapsulates each one,and makes them interchangeable. Strategy lets the algorithm vary independently from clients that use it.

    然后看看这种设计模式的组成,

    一般的,策略模式主要分为以下三个角色: 
        1. 环境角色(Context):持有一个策略类引用

             存在的优点:(1)必要时可以增加系统的安全性,减少代码的冗余(下文有详解)。
        2. 抽象策略(Strategy):定义了多个具体策略的公共接口,具体策略类中各种不同的算法以不同的方式实现这个接口;Context使用这些接口调用不同实现的算法。一般的,我们使用接口或抽象类实现。 
        3. 具体策略(ConcreteStrategy):实现抽象策略类中的相关的算法或操作。

    我贴上简单的实现

    抽象类(抽象策略)

    public abstract class AbstractStrategy {
        public abstract void algorithm();
    }

    具体策略-A

    public class ConcreteStrategyA extends AbstractStrategy {
    
        @Override
        public void algorithm() {
            System.out.println("Strategy A");
        }
    }

    具体策略-B

    public class ConcreteStrategyB extends AbstractStrategy {
    
        @Override
        public void algorithm() {
            System.out.println("Strategy B");
        }
    }

    环境角色怎么用的呢?

    public class Context {
        private AbstractStrategy strategy;
    
        public Context(AbstractStrategy strategy) {
            this.strategy = strategy;
        }
    
        public void algorithm() {
            this.strategy.algorithm();
        }
    }

    使用的时候我们这样用

    public static void main(String[] args) {
        //Strategy Pattern Demo
        Context context = new Context(new ConcreteStrategyA());
        context.algorithm();
    
        context = new Context(new ConcreteStrategyB());
        context.algorithm();
    }

    细心如你应该会想我使用如下代码也能实现,Context的存在是为了什么?

    AbstractStrategy abstractStrategy = new ConcreteStrategyA();
    abstractStrategy.algorithm();
    
    abstractStrategy = new ConcreteStrategyB();
    abstractStrategy.algorithm();

    这里我们看看第一种现象:

    修改抽象策略中的方法

    public abstract void algorithm(int number);

    修改具体策略的实现

    @Override
    public void algorithm(int number) {
        System.out.println(number);
    };

    看到这里你会不会觉得这个参数number有安全隐患,传进来的合法吗?于是我要判断,so,你可以每个具体的策略中都写一段相同的逻辑去判断下,或者传参时判断下,那么不想copy的你此刻是不是想找个地方统一判断一把,是的Context(译为上下文,在.NET中有DBContext。。。)此刻显示出重要性,我们大可在构造函数中去判断,那么我们总结下Context的第一个优点:必要时可以增加系统的安全性,减少代码的冗余。还有什么优点呢?需要我们自己去在实际的Coding中总结,希望大家共同探讨。

     这里需要和工厂模式进行比较,加以区别。

  • 相关阅读:
    Spring MVC之视图呈现
    Spring MVC之HandlerMap 初始化
    Spring MVC之DispatcherServlet请求处理
    合成模式
    缺省适配器
    适配器模式
    原始模型
    克隆 和 比较
    建造模式
    线段树
  • 原文地址:https://www.cnblogs.com/chenyongblog/p/5154393.html
Copyright © 2011-2022 走看看