开发者

The benefits of Composite Pattern over simple inheritance

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 inheritan开发者_Python百科ce 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.


One important difference becomes apparent in your example. Inheritance is, in most languages, a compile-time mechanism. You define the relationships of classes in your source-code.

Composition is often combined with inheritance (are rather polymorphism). You can decide at runtime how you compose complex objects, if the parts have a polymorphic interface.

Finally, it depends on the language used. In C++, inheritance should only be used for polymorphism, and never for code-reuse. In languages like Python this is not true. Here you can achieve the same thing with composition and inheritance.


I'd recommend you Head First Design Patterns book, the first chapter named Intro to Design Patterns talks about Strategy pattern and there is a very detail example which you can find out yourself about composition and why we favor composition over inheritance.


I Would Recommend you better u go through this pdf:-- http://userpages.umbc.edu/~tarr/dp/lectures/Composite-2pp.pdf this pdf will definately help you. Thanks.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜