• 策略模式 Strategy


    public Context(String strategyType)
    
    {
    
    switch(strategyType)
    
    {
    
    case "算法A":
    
         strategy=new ContextStrategyA();
    
         break;
    
    case "算法B":
    
         strategy=new ContextStrategyB();
    
         break;
    
    ...............
    
    }
    
    }

    DF对策略模式的定义是这样的:它定义了算法家族,分别封装起来,让它们之间可以相互替换,此模式让算法的变化不会影响到使用算法的客户(main函数)。

    abstract class Strategy
    
    {
    
    public abstract void AlgorithmInterface();
    
    }
    class ConcreteStratrgyA extends Strategy
    
    {
    
     @override
    
    public void AlgorithmInterface()
    
    {
    
       //算法A的具体实现。
    
    }
    
    }
    class ConcreteStrategyB extends Strategy
    
    {
    
     @override
    
    public void AlgorithmInterface()
    
    {
    
      //算法B的具体实现
    
    }
    
    }
    class Context
    
    {
    
    Strategy strategy;
    
    public Context(Strategy strategy)
    
    {
    
    this.strategy=strategy;
    
    }
    
    public void ContextInterface)
    
    {
    
    strategy.AlgorithmInterface();
    
    }
    
    }

    在Context类的构造方法中可以使用简单工厂模式,实现策略模式和简单工厂模式的结合。

    public static void main(String[] args)
    
    {
    
    Context context;
    
    context=new Context(new ContextStrategyA());
    
    context.ContextInterface();
    
    
    
    context=new Context(new ContextStrategyB());
    
    context.ContextInterface();
    
    }
  • 相关阅读:
    vue-修改vue项目运行端口号
    任正非521央视采访全文
    是施压还是真的决裂?
    贸易战风波继续
    华为对封杀的态度和格局
    美国封锁对华为的影响
    布鲁克斯法则 (Brooks's Law)
    2019第20周日
    如何让自己走的更远
    如何应对中年危机
  • 原文地址:https://www.cnblogs.com/wangjiyuan/p/Strategy.html
Copyright © 2020-2023  润新知