Reputation: 2726
I'm working on a natural language processing project (in C#), where I need to refer to words by their indices rather than the strings themselves to speed things up. For example, the sentence "i am what i am"
should be stored as "0 1 2 0 1"
.
In this project, there are many classes that store sentences this way. To deal with this, I initially planned to implement a singleton class named Codebook
for it, so that in any place in my project, whenever I needed to convert the string of a word to its index (or get string by index), all I need to say is Codebook.Instance.Convert(n)
or something like that.
However, this causes trouble because I need to have several Codebook
s for different use (e.g, one for Chinese, one for English, and even one for part-of-speech tagging labels), so I thought of another way to to it. At the very top of my project structure, I create an instance of Codebook
, and then I pass it all around. In this way, almost every method that deals with sentences will have a Codebook
parameter. Since in C#, passing an object is in the form of reference rather than its real content, all appearance of the Codebook
objects all refer to the same one.
So my question is, will the second approach cause problem, if the Codebook
object is passed multiple times? I am concerned because, the usage of index instead of string itself is intensive in my project. I know that the singleton approach is okay to deal with my problem, but as I said, I am not allowed to use that. So I need to know if the second approach is okay when say, there's a long chain of method invoking along which the same Codebook
object should pass.
Upvotes: 1
Views: 116
Reputation: 27934
Normally I would suggest to use dependency injection through the constructor. Just pass the codebook to the constructor and keep a readonly reference in your class. This way you are sure you have the right code book in all your classes. A singleton approach would also deal with the problem, however it will be harder to test and maintain.
public class MyBusiness{
public MyBusiness(Codebook codebook){
Codebook = codebook;
}
private readonly Codebook Codebook;
...
}
Upvotes: 1
Reputation: 6775
You said above in one of the comments that since you need code book in different languages you can't use singleton. How about creating another class and having List of CodeBook (Or Dictionary with language as the key so you can fetch it appropriately) as one of its properties and make the new class as singleton. This way you always get the same object back but also have a collection of Codebooks.
Upvotes: 0