在C#中为需求设计我的类的最佳方法 [英] Best way to design my classes for the requirement in C#

查看:64
本文介绍了在C#中为需求设计我的类的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



有人可以帮助您设置以下要求的最佳方法。我不想多次实现相同的方法。有人能告诉我哪种设计模式更适合它。



老虎:步行(),跑步(),游泳()

马:Run(),Swim()

乌龟:步行(),游泳()

鱼:游泳()



谢谢,

Ramana



我尝试过:



我自己找不到更好的方法。

解决方案

你看过抽象类,虚拟类和继承吗?

您应该使用类继承(抽象类,解决方案1中建议的虚拟类)和Factory模式来隐藏接口背后的实现细节 - 这是一个没有接口的示例: C#和VB中的工厂方法.NET设计模式 - dofactory.com [ ^ ]



一旦你的动物准备好样本 - 你可以让每个类实现一个接口,只在工厂的返回类型中显示该接口。



此模式在项目允许您将动物类设置为内部并使其详细信息对外界不可见(如果您最终使用了接口和工厂类,则应该公开它们正确的设计)。


公共抽象类生物

{

public virtual void Walk()

{



}



public virtual void Run()

{< br $>


}



public virtual void游泳()

{



}

}

公共类Tiger:生物

{



}

公共类马:生物

{

公共覆盖void Walk()

{

抛出新的例外(可以走路);

}

}

public class Fish:Creature

{

public override void Walk()

{

抛出新的异常(Can步行);

}



公共覆盖无效运行()

{

抛出新的异常(可以运行);

}

}

公共类乌龟:生物

{

public override void Run()

{

抛出新的异常(可以运行);

}

}


Hi,
Can someone help with the best way of designing the classes for the below requirement. I don't want to implement the same method multiple times. Can someone tell me even which design patter suits it better.

Tiger: Walk(), Run(), Swim()
Horse: Run(), Swim()
Tortoise: Walk(),Swim()
Fish: Swim()

Thanks,
Ramana

What I have tried:

Couldn't find a better way myself.

解决方案

Have you looked into abstract classes, virtual classes, inheritence?


You should use class inheritance (abstract classes, virtual classes as suggested in solution 1) and the Factory pattern to hide the details of the implementation behind interfaces - here is an example without interfaces: Factory Method .NET Design Pattern in C# and VB - dofactory.com[^]

Once you have the sample in place with your animals - you can have each class implement an interface and make only that interface in the return type of the factory visible.

This pattern implemented in a Library project allows you to set the animal classes to internal and make their details invisible to the outside world (only the interfaces and the Factory class should be public if you end up with the right design).


public abstract class Creature
{
public virtual void Walk()
{

}

public virtual void Run()
{

}

public virtual void Swim()
{

}
}
public class Tiger : Creature
{

}
public class Horse : Creature
{
public override void Walk()
{
throw new Exception("Can walk");
}
}
public class Fish : Creature
{
public override void Walk()
{
throw new Exception("Can walk");
}

public override void Run()
{
throw new Exception("Can Run");
}
}
public class Tortoise : Creature
{
public override void Run()
{
throw new Exception("Can Run");
}
}


这篇关于在C#中为需求设计我的类的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆