gpt4 book ai didi

java - OOPS ( JAVA ) 中的类设计

转载 作者:行者123 更新时间:2023-12-01 16:13:10 27 4
gpt4 key购买 nike

  1. 有没有办法从接口(interface)中删除totalPermutationCount(),因为该方法的唯一目的是从具体类中获取permutationCombination值,如果有更多的具体类或更多的实例变量,那么接口(interface)将变得团 block 和大。
  2. 除了构造函数之外,是否还有其他最佳方法可以为整个类所依赖的实例变量赋值。

引用我的使用方法,请帮助我变得更好。

界面

interface Word {
void performPermutation();
int totalPermutationCount();
}

接口(interface)实现

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());
}
}

最佳答案

以下内容可以帮助您解答疑问:

  1. 如果从接口(interface)中删除totalPermutationCount方法,您将失去从接口(interface)类实现的抽象的好处。如果您仍然需要这样做,那么您将需要使用 WordImpl wordImplReference = new WordImpl("home");在你的主要方法中。

  2. 在这种情况下,通过构造函数分配会更好。可以使用WordImpl类中的Set方法进行设置,但需要在Interface中添加setWord方法。

关于java - OOPS ( JAVA ) 中的类设计,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62481617/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com