背景
示例
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();
}
}
}
网友评论