小编典典
优先考虑组成而不是继承。
解决方案考虑到可能还有另一种类型的单词可能需要WordLengthSupport。
类似地,可以创建和实现其他接口,并且各种单词类型可以具有这些接口的混合和匹配。
。
public class WordLength {
private int length = 0;
public int getLength(){return length};
public void setLength(int length){this.length = length};
}
。
public interface WordLengthSupport {
public WordLength getWordLength();
}
。
public class BetterWord extends AbstractWord
implements WordLengthSupport {
WordLength wordLength;
public WordLength getWordLength() {
if(wordLength==null) {
// each time word changes
// make sure to set wordLength to null
calculateWordLength();
}
return wordLength;
}
private void calculateWordLength() {
// This method should be
// called in constructor
// or each time word changes
int length = // based on the variable word calculate Length..
this.wordLength = new WordLength();
this.wordLength.setLength(length);
}
}
。
public class BetterWordDescriptor extends AbstractWord
implements WordLengthSupport {
WordLength wordLength;
public WordLength getWordLength(return wordLength);
public void setWordLength(WordLength wordLength) {
// Use this to populate WordLength of respective word
this.wordLength = wordLength;
}
}
。
策略模式定义 了一系列算法,将每个算法封装在一起,并使它们可互换。策略使算法独立于使用该算法的客户端而变化。
该解决方案不使用策略模式,但可以对其进行重构。
2020-10-09