抽象在C#或Java的id属性 [英] Abstracting an id attribute in C# or Java

查看:209
本文介绍了抽象在C#或Java的id属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我设计的API。下面是一个接口的一些示例方式:

I am designing an API. Here are some example methods from an interface:

Entry findEntry(int processId);
Entry findEntry(int processId, Filter filter);



其中,进程ID 指一些独特的识别信息。不过,我真的不知道是什么类型的进程ID 尚未

where processId refers to some unique identifying information. However I don't really know what the type of processId is yet.

我怎样才能抽象出来的元素像的东西标识

How can I abstract away an element like id of something?

最好我能想出是创建一个虚拟接口:

The best I could come up with is creating a dummy interface:

Entry findEntry(ProcessId id);
Entry findEntry(ProcessId, Filter filter);



不过,我担心上述的方法,我可能迫使API的客户端上操作过高的抽象水平。例如,进程ID平等的将不再工作(而如果他们使用INT的 - 它会)

However, I worry that with the above approach I may force the client of the API to operate on too high an abstraction level. For example, the equality of process id's will no longer work (whereas if they used int's - it would).

澄清的:我没有澄清的是,我写的只是接口(合同),将有可能由不同的团队后实施。这就是为什么我不能强制某些事情像equals方法。

Clarification: I failed to clarify that I am writing only the interfaces (contracts), to be implemented later, possibly by a different team. That is why I cannot enforce certain things like equals method.

推荐答案

泛型是你的朋友在这里

在方法本身是否合适。

Entry findEntry<TKey>(TKey processId);

或可能的类

public class EntryFinder<TKey>
{
  public Entry findEntry(TKey processId)
  {
     // Implementation
  }
}

修改:如果定义界面,你也可以有明确这一点,并把它留到接口的implemntors到。弄清楚他们想用来标识一个条目是什么类型

Edit: If you're defining the interface, you can also define this there and leave it to the implemntors of the interface to figure out what type they want to use to identify an Entry.

public interface IEntryFinder<TKey>
{
  Entry findEntry(TKey processId);
}



用法:

Usage:

// Foo's are looked up by integer
public class FooEntryFinder : IEntryFinder<int>
{
  public Entry findEntry(int processId)
  {
     // Implementation
  }
}
// Baa's are looked up by string
public class BaaEntryFinder : IEntryFinder<string>
{
  public Entry findEntry(string processId)
  {
     // Implementation
  }
}

这篇关于抽象在C#或Java的id属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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