Design Pattern: Strategy pattern; Design Pattern strategy
I. Definition
The policy mode defines the algorithm family and encapsulates them separately so that they can be replaced with each other. This mode makes the algorithm changes independent of the customers who use the algorithm.
Ii. Design Principles
1. Identify potential changes in the application and separate them from those that do not need to be changed.
2. Programming for interfaces, rather than implementing programming.
3. Multi-Purpose Combination and less inheritance.
Iii. Example
/// <Summary>
/// Duck
/// </Summary>
Public abstract class Duck
{
Protected IFlyBehavior flyBehavior;
Protected IQuackBehavior quackBehavior;
Public Duck ()
{
}
Public abstract void Display ();
Public void initialize mfly ()
{
FlyBehavior. Fly ();
}
Public void initialize mquack ()
{
QuackBehavior. Quck ();
}
Public void setFlyBehavior (IFlyBehavior fb)
{
FlyBehavior = fb;
}
Public void setQuckBehavior (IQuackBehavior qb)
{
QuackBehavior = qb;
}
Public void Swim ()
{
Console. WriteLine ("all ducks can swim! ");
}
}
/// <Summary>
/// Flight Behavior
/// </Summary>
Public interface IFlyBehavior
{
Void Fly ();
}
Public class FlyNoWay: IFlyBehavior
{
Public void Fly ()
{
Console. WriteLine ("no fly! ");
}
}
Public class FlyWithWings: IFlyBehavior
{
Public void Fly ()
{
Console. WriteLine ("Fei! ");
}
}
Public class FlyRocketPower: IFlyBehavior
{
Public void Fly ()
{
Console. WriteLine ("Rocket accelerated flight! ");
}
}
/// <Summary>
/// Green-headed duck
/// </Summary>
Public class MallardDuck: Duck
{
Public MallardDuck ()
{
FlyBehavior = new FlyWithWings ();
QuackBehavior = new Quack ();
}
Public override void Display ()
{
Console. WriteLine ("I'm a green duck! ");
}
}
/// <Summary>
/// Model duck
/// </Summary>
Public class ModelDuck: Duck
{
Public ModelDuck ()
{
FlyBehavior = new FlyNoWay ();
QuackBehavior = new MuteQuack ();
}
Public override void Display ()
{
Console. WriteLine ("I am a model Duck ");
}
}
Static void Main (string [] args)
{
Duck muteQuack = new MallardDuck ();
MuteQuack. parse mfly ();
Duck model = new ModelDuck ();
Model. parse mfly ();
Model. setFlyBehavior (new FlyRocketPower ());
Model. parse mfly ();
Console. ReadLine ();
}
Source code download
Reprinted please indicate from: shining lucky stars
Address: http://www.cnblogs.com/dongyang
If reprinted, keep the original address. Thank you for your cooperation.