2 ms·
Ok, let's see... this is a draft and I don't have a compiler here, so I may write something wrong, but it would be something like this. Assuming that you don't
by gordaco 12y ago
Ok, let's see... this is a draft and I don't have a compiler here, so I may write something wrong, but it would be something like this. Assuming that you don't want to use simply a translation table, and you really need different code for each element from the enum, you would first create an interface:
public interface ILanguage {
String convert(int num);
}
Then you would subclass for each language:
public class SpanishLanguage implements ILanguage {
public String convert(int num) {
String ret;
switch (num) {
case 0: ret="cero";break;
case 1: ret="uno";break;
default: ret="~~~";
}
return ret;
}
}
And the same for English, German or whatever you want. Yes, it gets too verbose, that's why I'd prefer just a translation table... in any case, you can abstract common code for languages that only implement translation for 1, 2 and others, and create more complex subclasses for different behaviours. But I digress...
Now that you have the interface, you would declare the enum as follows:
public enum Language {
SPANISH(new SpanishLanguage()), ENGLISH(new EnglishLanguage()), GERMAN(new GermanLanguage());
// This is a member instance.
private ILanguage translationImpl;
// And this is the one and only constructor.
public Language(ILanguage translationImpl) {
this.translationImpl=translationImpl;
}
public String convert(int number) {
return translationImpl.convert(number);
}
}
If you do this, you need to supply the implementation of the language to the constructor, otherwise your code fails to compile. So you can't add FRENCH or JAPANESE after GERMAN(new GermanLanguage()); you need FRENCH(new FrenchLanguage()), JAPANESE(new JapaneseLanguage()) and so on. Of course you can do JAPANESE(null), but it's immediately clear that you're doing it wrong.
I'm completely aware that there is a lot of Java-ness (in the bad sense) in this code, so maybe in C# you can do it more elegantly. I haven't touched C# for a good 10 years...
EDIT: formatting.