栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Java中的多继承设计问题

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

策略模式定义 了一系列算法,将每个算法封装在一起,并使它们可互换。策略使算法独立于使用该算法的客户端而变化。

该解决方案不使用策略模式,但可以对其进行重构。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/437982.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号