I am building an app where I print a word in different languages based on a user's selection from a dropdown menu. My current method works however is not efficient as I am getting the data from a nested class and requesting it from a completely different class which requires a line of code for each word in a nested class. How can I achieve this in a more efficient/easier way? Here is the basic format of said code:
public class words {
class example {
String english = "example";
String chinese = "example_in_chinese";
}
class example2 {
String english = "example2";
String chinese = "example2_in_chinese";
}
}
public class getWords {
words word = new words();
words.example example = word.new example();
words.example2 example2 = word.new example2();
*/ I have to repeat the above line for each of the 20
words I have in a nested class
/*
}
CodePudding user response:
Maybe you can use chain of responsibility design pattern to determine which language is appropriate to print.
It takes long to show with code but I will given hint to you.
Iterate over objects to find printable language with given dropdown value. If you can not find appropriate language for printing then ignore it.
https://www.tutorialspoint.com/design_pattern/chain_of_responsibility_pattern.htm
CodePudding user response:
I think you can try to use Map.
public class Words {
static Map<String, String> example1 = new HashMap<String, String>();
example1.put("english", "example");
example1.put("chinese", "example_in_chinese");
static Map<String, String> example2 = new HashMap<String, String>();
example2.put("english", "example2");
example2.put("chinese", "example2_in_chinese");
}
So you can just call
Words.example1.get("english");
Or even further, you can create an enum Language
enum Language {
ENGLISH, CHINESE
}
public class Words {
static Map<Language, String> example1 = new HashMap<Language, String>();
example1.put(Language.ENGLISH, "example");
example1.put(Language.CHINESE, "example_in_chinese");
static Map<Language, String> example2 = new HashMap<Language, String>();
example1.put(Language.ENGLISH, "example2");
example1.put(Language.CHINESE, "example2_in_chinese");
}
Words.example1.get(Language.ENGLISH);
Just to reduce typing error possibility.