gpt4 book ai didi

C#继承/多态

转载 作者:行者123 更新时间:2023-11-30 19:41:39 25 4
gpt4 key购买 nike

假设有以下类:

public class Animal
{
}

public class Dog : Animal
{
public void Bark()
{
}
}

public class Cat : Animal
{
public void Meow()
{
}
}


Animal cat = Cat();
Animal dog = Dog();
PatternIamLookingFor.DoSomething(cat); // -> Call Meow
PatternIamLookingFor.DoSomething(dog); // -> Call Bark

这可能吗?没有向 Animal 基类添加 MakeNoise() 之类的方法?

在我的应用程序中,我有一个 CatFactory 和一个 DogFactory,它们实现 AnimalFactory 并返回 Animals。厂里不能叫Meow/bark,拿到动物后也不能叫。

最佳答案

我可以想出几种方法来实现上述内容。

1。使用接口(interface)

如果您可以修改原始源代码,这可能是最好的选择。易于实现,易于维护。

public interface IDoSomething
{
void DoSomething();
}

public class Dog : Animal, IDoSomething
{
public void Bark()
{
}

void IDoSomething.DoSomething(){
Bark();
}
}

public class Cat : Animal, IDoSomething
{
public void Meow()
{
}

void IDoSomething.DoSomething(){
Meow();
}
}

2。使用 Adapters

如果您无法访问原始源代码,适配器可能是唯一的选择。您可以使用它们来“同步”代码访问 Cat 和 Dog 类的方式。您仍然可以像使用原始对象一样使用适配器,但使用更适合新代码需求的修改接口(interface)。创建一个工厂以根据父类型创建适当的适配器会相当简单。

public IDoSomething
{
void DoSomething()
{
}
}

public DoSomethingFactory
{

public static IDoSomething( Animal parent )
{
if ( typeof( parent ) is Dog )
return new DoSomethingDog( parent as Dog );
if ( typeof( parent ) is Cat )
return new DoSomethingCat( parent as Cat );
return null;
}

}

public DoSomethingDog : Dog, IDoSomething
{
Dog _parent;
public DoSomethingDog( Dog parent )
{
_parent = parent;
}

public void DoSomething()
{
_parent.Bark();
}
}

public DoSomethingCat : Cat, IDoSomething
{
Cat _parent;
public DoSomethingCat( Cat parent )
{
_parent = parent;
}

public void DoSomething()
{
_parent.Meow();
}
}

除了这两个明显的实现之外,您可能还需要考虑以下这些:

  • 使用 Decorators动态增强类的功能。 (类似于上面的“包装器”方法,但更干净地融入类结构中。)

  • 实现一系列 Command您的类可以动态处理的对象:

    cat.Do( new MakeNoiseCommand() ); // Handled as "meow"
    dog.Do( new MakeNoiseCommand() ); // Handled as "bark"
  • 允许类似于 Mediator 的内容根据 Animal 的类型等转发请求:

    public class AnimalMediator
    {
    public void MakeNoise( Animal animal )
    {
    if ( typeof( animal ) is Dog ) (animal as Dog).Bark();
    else if ( typeof( animal ) is Cat ) (animal as Cat).Meow();
    }
    }

关于C#继承/多态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19102724/

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