zoukankan      html  css  js  c++  java
  • 我也设计模式——23.Strategy

    这个模式是对模板方法的简单包装,可以看到,只是多了一个Context类这个包装器。


    以上UML图的代码很好实现,关键是Client如何使用Context类:

                Strategy s = new ConcreteStrategyA();

                Context context 
    = new Context();
                context.Strategy 
    = s;
                context.ContextInterface();

    客户端必须知道所有的策略类,从而会造成很多策略类,这是该模式的缺点。

    基于委托的策略模式,可以解除Context与Strategy的耦合,于是ConcreteStrategyA与ConcreteStrategyB可以不是相同的父类。

        public delegate void strategy();

        
    public class ContextUseingDelegate
        
    {
            
    public strategy myStrategy;

            
    public void ContextInterface()
            
    {
                myStrategy();
            }

        }


        
    public class StrategyClassA
        
    {
            
    public void ConcreteStrategyA() { }
        }


        
    public static class StrategyClassB
        
    {
            
    public static void ConcreteStrategyB() { }
        }

    于是在Client这么调用代码:

                StrategyClassA sa = new StrategyClassA();

                ContextUseingDelegate cud 
    = new ContextUseingDelegate();
                cud.myStrategy 
    += new strategy(sa.ConcreteStrategyA);
                cud.myStrategy 
    += new strategy(StrategyClassB.ConcreteStrategyB);
                cud.ContextInterface();
  • 相关阅读:
    OpenCV使用边缘提取、腐蚀、轮廓进行车牌定位
    How To Move Or Rebuild A Lob Partition
    Hadoop入门进阶步步高(三)-配置Hadoop
    [学习笔记]整体DP
    leetcode404
    leetcode349
    leetcode383
    leetcode453
    leetcode455
    leetcode167
  • 原文地址:https://www.cnblogs.com/Jax/p/913953.html
Copyright © 2011-2022 走看看