我想构建一个很好的API(C#),让人们更容易消费,我想我以前见过这个并想知道如何做到这一点:
MyNamespace.Cars car = null;
if(someTestCondition)
car = new Honda();
else
car = new Toyota();
car.Drive(40);
Run Code Online (Sandbox Code Playgroud)
这可能吗?如果是这样,需要做什么?
Otá*_*cio 10
Interface Car
{
void Drive(int miles);
}
class Honda : Car
{
...
}
class Toyota : Car
{
...
}
Run Code Online (Sandbox Code Playgroud)
你可以用几种不同的方式做到这一点.您可以声明一个抽象基类,也可以使用对象实现的接口.我相信"C#"首选方法是拥有一个接口.就像是:
public interface ICar
{
public Color Color { get; set; }
void Drive(int speed);
void Stop();
}
public class Honda : ICar
{
#region ICar Members
public Color Color { get; set; }
public void Drive(int speed)
{
throw new NotImplementedException();
}
public void Stop()
{
throw new NotImplementedException();
}
#endregion
}
public class Toyota : ICar
{
#region ICar Members
public Color Color { get; set; }
public void Drive(int speed)
{
throw new NotImplementedException();
}
public void Stop()
{
throw new NotImplementedException();
}
#endregion
}
Run Code Online (Sandbox Code Playgroud)
我看到每个人都在推动界面/抽象基类更改.您提供的伪代码或多或少意味着您已经实现了这一点.
我会做出别的东西:
您将需要创建一个"CarFactory",它将返回基类/接口的特定实现.Create方法可以将您的测试条件作为参数,以便您创建正确的汽车.
编辑:这是MSDN的链接 - http://msdn.microsoft.com/en-us/library/ms954600.aspx
编辑:请参阅其他链接的评论.
| 归档时间: |
|
| 查看次数: |
378 次 |
| 最近记录: |