复合模式对简单继承的好处 [英] The benefits of Composite Pattern over simple inheritance

查看:78
本文介绍了复合模式对简单继承的好处的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我想说明我们要实现一个文件系统。
所以基本上我们需要文件和文件夹。
我们可以使用复合模式,而文件文件夹类继承基础界面和文件夹 class持有一个接口类型集合。



但是,对于简单的继承来说,这看起来像(对我来说),继承也可以做同样的事情。
如果文件是根类,文件夹继承自文件文件夹可以收藏文件 s,故事结尾。



我是否缺少某些东西?

解决方案


如果File是根类和文件夹继承文件,文件夹可以收藏文件


这本质上是复合模式,即使你不调用它: - )



除了您的变体中,Folder将继承不能(或更糟糕的是:不应该)使用的特定于文件的功能。所以你最终会使你的实现变得复杂,客户端无法将字节附加到文件夹的结束等。



FYI是GoF书的续集, Pattern Hatching ,讨论了使用各种模式(包括Composite)的文件系统的实现。强烈推荐阅读。


I am trying to figure out why composite is better than a simple inheritance.

For example, lets say we want to implement a file system. So basically we need files and folders. We can use the composite pattern while File and Folder classes inherit the base interface and Folder class holds an interface type collection.

But it looks like (to me anyway) that simple inheritance can do the same thing. If File is the root class and Folder inherits from File, the Folder can hold collection of Files, end of story.

Am I missing something?

解决方案

if File is the root class and Folder inherit File, the Folder can hold collection of Files

This is essentially the Composite pattern, even if you don't call it like that :-)

Except that in your variation, Folder will inherit file-specific functionality which it can't (or worse: shouldn't) use. So you end up complicating your implementation to ensure that e.g. clients can't append bytes to the "end" of your folder etc.

FYI, the sequel to the GoF book, Pattern Hatching, discusses the implementation of a file system using various patterns, including Composite. Highly recommended read.

这篇关于复合模式对简单继承的好处的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆