首页 > 代码库 > 策略模式和简单工厂

策略模式和简单工厂

策略算法类:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace StrategyDemo
{
    abstract class Strategy
    {
        public abstract void BillInterface();
    }

    class ConcreteStrategyA : Strategy
    {
        public override void BillInterface()
        {
            Console.WriteLine("算法A的实现");
        }
    }

    class ConcreteStrategyB : Strategy
    {
        public override void BillInterface()
        {
            Console.WriteLine("算法B的实现");
        }
    }

    class ConcreteStrategyC : Strategy
    {
        public override void BillInterface()
        {
            Console.WriteLine("算法C的实现");
        }
    }
}

上下文类封装简单工厂

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

namespace StrategyDemo
{
    class Context
    {
        Strategy strategy;
        public const int TYPEA = 1;
        public const int TYPEB = 2;
        public const int TYPEC = 3;
        public Context(int i)
        {
            switch (i)
            {
                case TYPEA:
                    strategy = new ConcreteStrategyA();
                    break;
                case TYPEB:
                    strategy = new ConcreteStrategyB();
                    break;
                case TYPEC:
                    strategy = new ConcreteStrategyC();
                    break;
                default:
                    break;
            }
        }

        //上下文接口
        public void ContextInterface()
        {
            strategy.BillInterface();
        }
    }
}

客户端调用:

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

namespace StrategyDemo
{
    //策略模式和简单工厂一起使用
    class Program
    {
        static void Main(string[] args)
        {
            Context context;
            context = new Context(Context.TYPEA);
            context.ContextInterface();
            context = new Context(Context.TYPEB);
            context.ContextInterface();
            context = new Context(Context.TYPEC);
            context.ContextInterface();
            Console.ReadKey();
        }
    }
}


策略模式和简单工厂