• 策略模式


    今天研究一下策略模式。

    Strategy Pattern UML

    示例程序如下:

    Strategy.cs

    namespace StrategyPatternExample
    {
        public interface Strategy
        {
            int Execute(int a, int b);
        }
    }
    

    Context.cs

    namespace StrategyPatternExample
    {
        public class Context
        {
            private Strategy strategy;
    
            public Context(Strategy strategy)
            {
                this.strategy = strategy;
            }
    
            public int ExecuteStrategy(int a, int b)
            {
                return strategy.Execute(a, b);
    
            }
        }
    }
    

    ConcreteStrategyAdd.cs

    using System;
    
    namespace StrategyPatternExample
    {
        class ConcreteStrategyAdd : Strategy
        {
            public int Execute(int a, int b)
            {
    
                Console.WriteLine("Called ConcreateStrategyAdd's execute. a = {0}, b = {1}", a, b);
                return a + b;
            }
    
    
        }
    }
    

    ConcreteStrategySubtract.cs

    using System;
    
    namespace StrategyPatternExample
    {
        class ConcreteStrategySubtract:Strategy
        {
            public int Execute(int a, int b)
            {
                Console.WriteLine("Called ConcreteStrategySubtract's execute, a = {0}, b = {1}",a, b);
                return a - b;
            }
        }
    }
    

    Program.cs

    using System;
    
    namespace StrategyPatternExample
    {
        class Program
        {
            static void Main(string[] args)
            {
                Context context;
    
                context = new Context(new ConcreteStrategySubtract());
                int resultSub = context.ExecuteStrategy(2, 1);
                Console.WriteLine("ConcreteStrategySubtract's result is {0}", resultSub);
                Console.WriteLine();
    
                context = new Context(new ConcreteStrategyAdd());
                int resultAdd = context.ExecuteStrategy(3, 4);
                Console.WriteLine("ConcreteStrategyAdd's result is {0}", resultAdd);
            }
        }
    }
    

    result:

    

  • 相关阅读:
    Java判断一个字符是数字或字母
    java数组和字符串相互转换
    java 字符串截取的三种方法
    Templates && Algorithms
    挖坑——未完成题目列表QwQ
    作业_2018.08.25
    BZOJ1008 [HNOI2008]越狱 (快速幂,组合)
    UR #3 核聚变反应强度( gcd )
    A Super Hero
    NOIP2015 pj
  • 原文地址:https://www.cnblogs.com/edmundli/p/strategypattern.html
Copyright © 2020-2023  润新知