策略模式

策略模式的使用场景:

1.一个系统中有许多类,他们的区别在于行为不同,则可以通过策略模式,可以动态的让一个对象选择其中的一个。

2.一个系统需要动态地在几种算法中选择一种。例如:打折、返佣等。

3.可以将一些复杂的条件语句,使用策略模式简化。

4.让客户端决定使用相应的策略模式。

UML图:

示例代码:

    public abstract class RedisHelper
    {
        public abstract string Get(string key);
    }
    public class StackExchageRedis : RedisHelper
    {
        public override string Get(string key)
        {
            return "通过StackExchage获取缓存";
        }
    }
    public class CSRedis : RedisHelper
    {
        public override string Get(string key)
        {
            return "通过CSRedis获取缓存";
        }
    }
    public class RedisContext
    {
        private RedisHelper redisHelper;

        public RedisContext(RedisHelper redisHelper)
        {
            this.redisHelper = redisHelper;
        }

        public string GetCache(string key)
        {
            return this.redisHelper.Get(key);
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            RedisContext context = new RedisContext(new StackExchageRedis());
            Console.WriteLine(context.GetCache("aa"));

            RedisContext contextA = new RedisContext(new CSRedis());
            Console.WriteLine(contextA.GetCache("aa"));

            Console.ReadKey();
        }
    }
原文地址:https://www.cnblogs.com/chenyishi/p/9103528.html