- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
假设有以下类:
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,拿到动物后也不能叫。
最佳答案
我可以想出几种方法来实现上述内容。
如果您可以修改原始源代码,这可能是最好的选择。易于实现,易于维护。
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();
}
}
如果您无法访问原始源代码,适配器可能是唯一的选择。您可以使用它们来“同步”代码访问 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/
我来自 Asp.Net 世界,试图理解 Angular State 的含义。 什么是 Angular 状态?它类似于Asp.Net中的ascx组件吗?是子页面吗?它类似于工作流程状态吗? 我听到很多人
我一直在寻找 3 态拨动开关,但运气不佳。 基本上我需要一个具有以下状态的开关: |开 |不适用 |关 | slider 默认从中间开始,一旦用户向左或向右滑动,就无法回到N/A(未回答)状态。 有人
我是一名优秀的程序员,十分优秀!