利用反射优化简单工厂

简单工厂的具体介绍可以看这篇博客设计模式学习一创建型


namespace SampleFactoryandStrategyFactory
{
    abstract class CashSuper
    {
        public abstract double acceptCash(double money);
    }
    //具体的算法策略
    class CashNormal: CashSuper
    {
        public override double acceptCash(double money)
        {
            return money;
        }
    }
    class CashRebate:CashSuper
    {
        private double moneyRebate=1d;
        public CashRebate(string moneyRebate1)
        {
            moneyRebate = double.Parse(moneyRebate1);
        }
        public override double acceptCash(double money)
        {
            return money * moneyRebate;
        }
    }
    
    class CashFactory
    {
        public static CashSuper createCashAccept(string type)
        {
            CashSuper cs = null;
            cs = (CashSuper)Assembly.Load("SampleFactoryandStrategyFactory").CreateInstance("SampleFactoryandStrategyFactory." + type);

    rn cs;
        }
    }
}
static void Main(string[] args)
        {
          //利用反射修改简单工厂,去除了switch判断的麻烦
            CashSuper cs = CashFactory.createCashAccept("CashNormal");
            Console.WriteLine(cs.acceptCash(90));
           
        }
已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页