java解决多继承的问题_Java中的多继承设计问题

小编典典

优先考虑组成而不是继承。

解决方案考虑到可能还有另一种类型的单词可能需要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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值