我试图用Startegy实现Head First Duck问题。我正在尝试实现Decoy Duck,它最初没有Quack或Fly的功能是通过调用默认构造函数来实现的(我知道这个鸭子没有飞行或嘎嘎的能力)。通过调用overriden consturctor对所有其他Duck进行初始化。在本书中,没有Fly的鸭子实现了FlyNoFly类,它实现了IFly接口。
对于我的解决方案,我没有使用这个课程。相反,我正在检查基础鸭类的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();
}
}
答案 0 :(得分:1)
不,这不是正确的实施。
策略模式用于避免在面向对象的代码中使用if (..)
。如果您使用FlyNoFly类,则可以避免if ( null )
检查,并且可以对所有Duck对象使用相同的构造函数。