oop – 桥模式 – 组合还是聚合?
发布时间:2020-12-14 04:49:11 所属栏目:百科 来源:网络整理
导读:我正在阅读一些关于设计模式的书籍,虽然有些人将抽象和实现之间的关系描述为一个组合,但有些人将其描述为聚合.现在我想知道:这取决于实施吗?关于语言?还是上下文? 解决方法 术语“组合物”和“聚集”意味着或多或少相同的事物并且可以互换使用.在描述容
我正在阅读一些关于设计模式的书籍,虽然有些人将抽象和实现之间的关系描述为一个组合,但有些人将其描述为聚合.现在我想知道:这取决于实施吗?关于语言?还是上下文?
解决方法
术语“组合物”和“聚集”意味着或多或少相同的事物并且可以互换使用.在描述容器类(例如列表,动态数组,映射和队列,其中元素都是相同类型)时,可以更频繁地使用聚合;然而,可以发现这两个术语都描述了根据其他类定义的类,无论这些类型是同质的(所有相同的类型)还是异类的(不同类型的对象).
为了更清楚: class Car { // ... private: Engine engine; Hood hood; }; // The car is *composed* of an engine and a hood. Hence,composition. You are // also bringing together (i.e. *aggregating*) an engine and hood into a car. 抽象和实现之间的关系通常意味着继承,而不是组合/聚合;通常,抽象是一个接口或虚拟基类,实现是一个实现给定接口的完全具体的类.但是,为了使事情变得混乱,组合/聚合可以是接口的一部分(例如,因为您可能需要设置/获取用作构建块的对象),它们也是实现的方法(因为您可以使用委托为您的实现中的方法提供定义). 为了更清楚: interface Car { public Engine getEngine(); public Hood getHood(); public void drive(); } // In the above,the fact that a car has these building blocks // is a part of its interface (the abstraction). class HondaCivic2010 implements Car { public void drive(){ getEngine().drive(); } // ... } // In the above,composition/delegation is an implementation // strategy for providing the drive functionality. 既然你已经标记了你的问题“桥”,我应该指出桥模式的定义是一种模式,你使用组合而不是继承来允许多个不同级别的变化.我在大学学到的一个例子……使用继承你可能有类似的东西: class GoodCharacter; class BadCharacter; class Mage; class Rogue; class GoodMage : public GoodCharacter,Mage; class BadMage : public BadCharacter,Mage; class GoodRogue : public GoodCharacter,Rogue; class BadRogue : public BadCharacter,Rogue; 正如你所看到的,这种事情非常疯狂,而且你得到了一些荒谬的课程.桥梁模式也是这样,看起来像: class Personality; class GoodPersonality : public Personality; class BadPersonality : public Personality; class CharacterClass; class Mage : public CharacterClass; class Rogue : public CharacterClass; class Character { public: // ... private: CharacterClass character_class; Personality personality; }; // A character has both a character class and a personality. // This is a perfect example of the bridge pattern,and we've // reduced MxN classes into a mere M+N classes,and we've // arguably made the system even more flexible than before. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- FLEX+FMS,实现H264的视频传输,变得如此简单
- arcgis server 数据注册 “the data item is inaccessible”
- xcode – CoreData:注释:无法加载优化模型(React Native)
- regex – 如何清除回车和Postgresql中的新行?
- 在xml文件中,不能直接使用<和&,必须进行转义后才能使
- postgresql 预写式日志(Write Ahead Long)
- reactos操作系统实现(104)
- Oracle手边常用70则脚本知识汇总
- playframework – Play Framework需要很长时间来解决依赖关
- 如何分析oracle表是否被人删除或者更新过?