美文网首页
{C#}设计模式辨析.策略

{C#}设计模式辨析.策略

作者: 码农猫爸 | 来源:发表于2021-08-13 05:12 被阅读0次

    背景

    • 策略作为算法,可自由替换

    示例

    using System.Collections.Generic;
    using static System.Console;
    
    namespace DesignPattern_Strategy
    {
        public interface IStrategy
        {
            void Sort(List<string> names);
        }
    
        public class QuickSort : IStrategy
        {
            public void Sort(List<string> names)
                => WriteLine("Quick sort is executed.");
        }
    
        public class BubbleSort : IStrategy
        {
            public void Sort(List<string> names)
                => WriteLine("Bubble sort is executed.");
        }
    
        public class Context
        {
            public IStrategy Strategy { get; set; }
    
            public Context(IStrategy strategy)
            {
                Strategy = strategy;
            }
    
            public void Sort(List<string> names)
            {
                Strategy.Sort(names);
                names.ForEach(x => WriteLine(x));
            }
        }
    
        class Program
        {
            static void Main(string[] args)
            {
                var quick = new QuickSort();
                var bubble = new BubbleSort();
                var context = new Context(quick);
    
                var list = new List<string> { "A", "B", "C" };
                context.Sort(list);
    
                context.Strategy = bubble;
                context.Sort(list);
    
                ReadKey();
            }
        }
    }
    

    相关文章

      网友评论

          本文标题:{C#}设计模式辨析.策略

          本文链接:https://www.haomeiwen.com/subject/jonqbltx.html