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?
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.