作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
<分区>
我曾尝试使用 Startegy 解决 Head First Duck 问题。我正在尝试实现 Decoy Duck,它最初没有 Quack 或 Fly 的功能是通过调用默认构造函数实现的(我知道这只鸭子没有 Fly 或 Quack 的能力)。所有其他 Ducks 都通过调用覆盖的构造函数来初始化。在书中,一只没有 Fly 的鸭子是用一个实现了 IFly 接口(interface)的 FlyNoFly 类实现的。
对于我的解决方案,我没有使用此类。相反,我正在检查鸭子基类的 Fly 属性是否为其传递了有效实例(通过 if(Fly != null) 。如果 Fly 具有有效引用,那么只有我在上调用 fly 方法那。否则我会抛出一条默认消息。
我想知道我的实现是否违反了任何设计原则/这是否是一个有效的实现。
谢谢图图蒙
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();
}
}
模板方法模式和策略模式做的事情大致相同。我了解它们之间的基本区别(模板方法是基于继承的,策略是基于组合的),但是对于何时选择一个而不是另一个有什么体面的指导方针?似乎他们做的事情基本相同。 最佳答案
我确实尝试过了解 Stratego/XT 的第一步。我在谷歌上搜索了很多,我发现的所有网络资源在开始时似乎都取得了足够大的飞跃,以至于我无法建立联系。让我解释一下。 我是这样理解抽象语法树的: Min
我已经能够通过 GitHub 项目使用 node.js 和 passport.js 连接到 Facebook:https://github.com/jaredhanson/passport-faceb
我是一名优秀的程序员,十分优秀!