我試圖用Startegy實現Head First Duck問題。我試圖實現誘餌鴨,它基本上不具備通過調用默認構造函數(我知道這個鴨子沒有飛行或嘎嘎能力)實現的設施。所有其他鴨子都通過調用覆蓋構造函數來初始化。在這本書中,一個沒有Fly的鴨子是通過實現IFly接口的FlyNoFly類實現的。這是一個正確的策略實施
對於我的解決方案,我沒有使用這個類。相反,我正在檢查基類duck類中的Fly propery是否傳遞了一個有效的實例(通過if(Fly!= null)。如果Fly具有有效的引用,那麼只有我正在調用fly方法這一點。否則,我舉辦了一個默認的消息。
我想知道我的執行是否違反任何設計原理/這是否是一個有效的執行。
感謝 TutuMon
public abstract class Duck
{
public IFlyable Fly { get; set; }
public IQuackable Quack { get; set; }
public void PerformQuack()
{
//Is this checking valid as per OO?
if (Quack != null)
Quack.Quack();
else
Console.WriteLine("Quack Operation Not supported");
}
public void PerformFly()
{
//Is this checking valid as per OO?
if (Fly != null)
Fly.Fly();
else
Console.WriteLine("Fly Operation not supported");
}
public abstract void Swim();
}
public class MallardDuck : Duck
{
public MallardDuck()
{
}
public MallardDuck(IFlyable fly, IQuackable quack)
{
Fly = fly;
Quack = quack;
}
public override void Swim()
{
Console.WriteLine("Mallard Duck is Swimming");
}
}
//No Fly and Quack behaviour by default
public class DecoyDuck : Duck
{
public DecoyDuck()
{
}
public DecoyDuck(IFlyable fly, IQuackable quack)
{
Fly = fly;
Quack = quack;
}
public override void Swim()
{
Console.WriteLine("DecoyDuck Duck is Swimming");
}
}
public interface IFlyable
{
void Fly();
}
public class FlyWithWings : IFlyable
{
public void Fly()
{
Console.WriteLine("You are flying with wings");
}
}
public class RocketFly : IFlyable
{
public void Fly()
{
Console.WriteLine("Rocket Powered Fly");
}
}
public interface IQuackable
{
void Quack();
}
public class RealQUack :IQuackable
{
public void Quack()
{
Console.WriteLine("This is Real Quack");
}
}
public class PowerQuack : IQuackable
{
public void Quack()
{
Console.WriteLine("Powerful Quacking ");
}
}
public class Program
{
public static void Main(string[] args)
{
Duck mallard = new MallardDuck
{Fly=new FlyWithWings(),Quack=new RealQUack()}
mallard.PerformQuack();
mallard.PerformFly();
// He can't Quack or Fly by default
// So i am calling the default constructor.
Duck decoy = new DecoyDuck();
decoy.PerformQuack();
decoy.PerformFly();
// Adding behaviours on the fly
decoy.Fly = new RocketFly();
decoy.Quack = new PowerQuack();
decoy.PerformQuack();
decoy.PerformFly();
Console.Read();
}
}
我認爲StackExchange網站[Code Review](http://codereview.stackexchange.com)更適合這類問題。 – 2012-05-04 13:12:15