策略模式

作者:追风剑情 发布于:2016-6-5 14:55 分类:设计模式

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

namespace StrategyTest
{
    class Program
    {
        static void Main(string[] args)
        {
            Context context = new Context(new StrategyA());
            context.operate();

            context = new Context(new StrategyB());
            context.operate();

            context = new Context(new StrategyC());
            context.operate();

            Console.Read();
        }
    }

    interface IStrategy
    {
        void operate();
    }

    class StrategyA : IStrategy
    {
        public void operate()
        {
            Console.WriteLine("执行策略A");
        }
    }

    class StrategyB : IStrategy
    {
        public void operate()
        {
            Console.WriteLine("执行策略B");
        }
    }

    class StrategyC : IStrategy
    {
        public void operate()
        {
            Console.WriteLine("执行策略C");
        }
    }

    class Context
    {
        private IStrategy strategy;

        public Context(IStrategy strategy)
        {
            this.strategy = strategy;
        }

        public void operate()
        {
            strategy.operate();
        }
    }
}

运行效果

11111.jpg

标签: Algorithms

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号