new design pattern -- strategy pattern
for design pattern , i always has an impression that we would not find the advantages and disadvantages if we don't use them in our projects.
i don't have many opportunities to use them so everytime i learn a design pattern , i just know how to use it , but i can't find that why i should use it , this design pattern are fit for what kind of situation.....
but i should not stop learning just becuase i don't have this opportunities...
Today , I learn about design pattern --- strategy pattern
just think that: there is a duck super class include serveral functions
1. fly()
2. quack()
and there are serveral classes which are inherited from this super class, that mean all these classes would inherited fly() and quack() functions.
but about fly() function , there maybe serveral way to fly, all the son classes would fly in one of these ways. so every son class would override the fly() function which would reduce the reuse ability of the code.
So , we can use strategy pattern, we get function which would always changes and abstract them into a class , and all these class would inherited from a interface so we can realise Polypeptide
public abstract class Duck
{
public FlyBehavior flyBehavior;
public void SetFlyBehavior(FlyBehavior be)
{
flyBehavior = be;
}
public void performFly()
{
flyBehavior.fly();
}
public void Sqack()
{
Console.WriteLine("ga ga ga .");
}
}
public interface FlyBehavior
{
void fly();
}
public class FlyWithWings: FlyBehavior
{
public void fly()
{
console.writeline("I can fly with my wings.");
}
}
public class FlyNoWay : FlyBehavior
{
public void fly()
{
console.writeline("I can not fly.");
}
}
public class MallardDuck:Duck
{
public MallarDuck()
{
flyBehavior = new FlyWithWings();
}
}
public class SimDuck: Duck
{
public SimDuck()
{
flyBehavior = new FlyNoWay();
}
}
in this way , we just abstract fly function into serveral classes and the class which inherited from Duck class can choose any of this class to perform fly()
we can also use setFlyBehavior() to set fly funtion whenever need.