【发布时间】:2020-06-20 04:22:09
【问题描述】:
- 有什么方法可以从接口中移除 totalPermutationCount(),因为该方法的唯一目的是从具体类中获取 permutationCombination 值,如果有更多具体类或更多实例变量,那么接口将变得团块和大。
- 除了构造函数之外,是否还有其他最佳方法可以为整个类所依赖的实例变量赋值。
参考我的使用方法,请帮助我变得更好。
界面
interface Word {
void performPermutation();
int totalPermutationCount();
}
接口实现
class WordImpl implements Word{
// "word" is to store the word from the user
private String word;
// "convert" is to convert the word into a char array to perform the logic
private char[] convert;
// "permutationCombination" is to find the total number of combination that is done
private int permutationCombination = 0;
// Constructor
public WordImpl(String wordCom){
setWord(wordCom);
}
//getter setter of word instance variable
public void setWord(String wordCom){
if(!wordCom.isEmpty() && wordCom.trim().length() > 0){
word = wordCom;
}else{
word = "Default";
}
convertToChar();
}
// convert the given word to char array
private void convertToChar(){
convert = new char[word.length()];
for(int i = 0 ; i < word.length() ; i++){
convert[i] = word.charAt(i);
}
}
public int totalPermutationCount(){
return permutationCombination;
}
// -------------------------------- Below is the Temporary Logic Ignore it ---------------------------------------------
private void performSwap(char[] list , int from, int to){
char temp;
temp = list[from];
list[from] = list[to];
list[to] = temp;
}
public void performPermutation(){
char[] list = convert.clone();
Set<String> listData = new HashSet<>();
System.out.println(convert);
for (int i = 0 ; i < word.length() ; i++){
for (int j = i + 1 , reverse = i - 1 ; j < word.length() || reverse >= 0 ; j++ , reverse--){
if(j < word.length()){
performSwap(list,i,j);
System.out.println(convertToString(list));
list = convert;
permutationCombination++;
}
if(reverse >= 0 && i != 0){
performSwap(list,i,reverse);
System.out.println(convertToString(list));
list = convert;
permutationCombination++;
}
}
}
}
// ----------------------------------------------------------------------------------------
private String convertToString(char[] list){
String value = "";
for(int i = 0 ; i < word.length() ; i++){
value = value + list[i];
}
return value;
}}
主类
public class MyClass {
public static void main(String args[]) {
Word wordImplReference = new WordImpl("home");
wordImplReference.performPermutation();
System.out.println(wordImplReference.totalPermutationCount());
}
}
【问题讨论】:
-
这看起来像是codereview.stackexchange.com的问题。
标签: java oop design-patterns class-design