策略模式

策略模式
特点:准备一组算法,分别封装到各自的类中,使他们可以互换
构成:
 策略上下文(Context),持有一个策略类的对象,提供动态设置策略方法
  抽象策略:通常是一个接口或者一个抽象类
 具体策略:包装了具体的算法和行为

示例代码:
namespace Strategy
{
    public abstract class Strategy
    {
        public abstract void WriteLog();
    }
}

namespace Strategy
{
    public class TxtLog : Strategy
    {
        public override void WriteLog()
        {
            Console.WriteLine("Txt");
            Console.Read();
        }
    }

    public class DbLog : Strategy
    {
        public override void WriteLog()
        {
            Console.WriteLine("DB");
            Console.Read();
        }
    }

    public class XmlLog : Strategy
    {
        public override void WriteLog()
        {
            Console.WriteLine("XML");
            Console.Read();
        }
    }
}

namespace Strategy
{
   public class Context
    {
       Strategy strategy;

       public Context(Strategy st)
       {
           this.strategy = st;
       }

       public void ContextStrategy()
       {
           strategy.WriteLog();
       }

       public void SetStrategy(Strategy st)
       {
           this.strategy = st;
       }
    }

}

static void Main(string[] args)
        {
            Context c = new Context(new TxtLog());
            c.ContextStrategy();


            c.SetStrategy(new DbLog());
            c.ContextStrategy();

            c.SetStrategy(new XmlLog());
            c.ContextStrategy();
        }

posted @ 2010-11-07 16:07  星空有我  阅读(238)  评论(1编辑  收藏  举报