策略模式

如果用一句话来概括简单工厂模式那便是:简单工厂模式解决了程序在运行时需要生成什么样的类来调用。那么策略模式要解决的就是,在程序运行时执行的方法当中,用什么样的算法来解决实际中产生的问题。

 

策略模式:它定义了算法家族,分别封装起来,让它们之间可以相互替换,此模式让算法的变化,不会影响到使用算法的客户。

 

实例:超市打折促销中的多种手段(一会儿打85折,一会儿9折,一会儿满25减5……),这些手段都是叫折扣(discount/on sale),只是具体的算法不一样而已。

其实现形式大体概括(用自己的话)便是:

  创建一个抽象类,在抽象类中声明一个抽象方法,然后再让继承抽象类的子类去实现这个抽象方法!

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Strategy
{
   abstract class Strategy
    {
       public abstract void AlgorithmInterface();
    }
}
声明一个抽象类和抽象方法
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Strategy
{
    class ConcreateStrategyA : Strategy
    {
        public override void AlgorithmInterface()
        {
            Console.Write("商品以85这促销!");
        }
    }
}
抽象方法A(85折)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Strategy
{
    class ConcreateStrategyB : Strategy
    {
        public override void AlgorithmInterface()
        {
            Console.Write("商品以9折促销!");
        }
    }
}
抽象方法B(9折)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Strategy
{
    class ConcreateStrategyC:Strategy
    {
        public override void AlgorithmInterface()
        {
            Console.Write("商品满25减5!");
        }
    }
}
抽象方法C(满25减5)
简单工厂类(根据实际需求,生成不同的类,调用与之对应的方法)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Strategy
{
    class Program
    {
        static void Main(string[] args)
        {
            Context context = new Context("");//传入"85","9"或者"25-5"
            context.ContextInterface();
        }
    }
}
控制台程序

 

在简单工厂类中,使用了switch判断传入的type来生成相应的对象,当需要增加一个方法的时候,就需要为switch语句增加一个条件分支。这里可以使用反射来消除这里大量的switch判断,当需要增加一个方法的时候,只需要在config文件中进行配置就可以了!

——抽象工厂模式

转载于:https://www.cnblogs.com/vichin/p/8394951.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值