gpt4 book ai didi

c# - 这是正确的战略实现吗

转载 作者:行者123 更新时间:2023-11-30 18:01:29 26 4
gpt4 key购买 nike

<分区>

我曾尝试使用 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();
}
}

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com