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

2021-08-13  本文已影响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();
        }
    }
}
上一篇下一篇

猜你喜欢

热点阅读