策略模式(Strategy) 面向接口编程是面向对象编程中一个最重要的原则,根据封装的原理,我们常常将易于变化的部分进行抽象,定义为接口.对于调用者而言,只需要知道接口的外部定义即可,具体的实现则不用理会.在设计模式中,策略模式就是这样的一个面向接口编程的最佳体现,它进行抽象的一部分是针对特定的算法,也就是所谓的策略.
public interface IFly
{
string Fly();
} // interface IFly
public class TrueFly : IFly
{
public string Fly()
{
return "Fly";
}
} // class TrueFly
public class FalseFly : IFly
{
public string Fly()
{
return "Run";
}
} // class FalseFly
public interface ISound
{
string Sound();
} // interface ISound
public class DogSound : ISound
{
public string Sound()
{
return "HA";
}
} // class DogSound
public class TigerSound : ISound
{
public string Sound()
{
return "WA";
}
} // class DogSound
public class Pig
{
protected IFly PigFly;
protected ISound PigSound;
public string Sleep()
{
return "Sleep";
}
public string Fly()
{
return PigFly.Fly();
}
public string Sound()
{
return PigSound.Sound();
}
} // class Pig
public class BlackPig : Pig
{
public BlackPig()
{
PigFly = new TrueFly();
PigSound = new DogSound();
}
} // class BlackPig
public class WhitePig : Pig
{
public WhitePig()
{
PigFly = new FalseFly();
PigSound = new TigerSound();
}
} // class WhitePig
策略模式的应用极为广泛,在.NET中自然不乏应用的例子.例如为集合类型Array和ArrayList提供的排序功能,就采用了Strategy模式.它是对比较算法进行了封装.