策略模式 ----- 排序例子

时间:2021-08-14 21:59:30

策略模式定义了一系列的算法,并将每一个算法封装起来,而且使它们还可以相互替换。策略模式让算法独立于使用它的客户而独立变化。(原文:The Strategy Pattern defines a family of algorithms,encapsulates each one,and makes them interchangeable. Strategy lets the algorithm vary independently from clients that use it.)

 
using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
using System.IO;
using System.Threading;
using System.IO.Ports;
using System.Data;

namespace Program
{
    public abstract class SortedStrategy//策略借口
    {
        public List<int> arr;
        public abstract void Sort();//对arr进行排序
    }
    public class QuickSortConcrete : SortedStrategy//快速排序实体
    {
        public override void Sort()
        {
            Console.WriteLine("对数组进行快速排序");
            arr.Sort();//假设这是快速排序
        }
    }
    public class HeapSortConcrete:SortedStrategy//堆排序实体
    {
        public override void Sort()
        {
            Console.WriteLine("对数组进行堆排序");
            arr.Sort();//假设这是堆排序
        }
    }
    public class ConText//使用的实体接口
    {
        List<int> arr = new List<int>();
        public void AddData(int t)
        {
            arr.Add(t);
        }
        public void Sort(SortedStrategy absStrategy)
        {
            absStrategy.arr = arr;
            absStrategy.Sort();
        }
        public void Display()
        {
            foreach (int i in arr)
                Console.WriteLine(i);
        }
    }
    class Program
    {
        static void Main()
        {
            ConText ct = new ConText();
            ct.AddData(3);
            ct.AddData(2);
            ct.AddData(1);
            ct.AddData(4);
            ct.Sort(new QuickSortConcrete());
//            ct.Sort(new HeapSortConcrete());
            ct.Display();
        }
    }
}