Reputation: 5445
I found a response that made me understand a bit more class compositioning.
class Engine
{
}
class Automobile
{
}
class Car extends Automobile // car "is a" automobile //inheritance here
{
Engine engine; // car "has a" engine //composition here
}
but isn't this a facade pattern? Isn't facade about making the class simpler by dividing into subclasses? What's then the difference between composition and facade?
Or maybe I get it wrong. The facade is a design pattern but the composition is more like a good practice to follow. Can we say that using facade is doing composition?
Upvotes: 4
Views: 2665
Reputation: 3665
The Facade Pattern is a design pattern used to change an interface not suited to your current needs into one that is more helpful. It encapsulates the other interface completely, not exposing it.
Some examples of use:
Upvotes: 0
Reputation: 4003
Composition combines N other objects in an object with the same API. So you could call the same method both on the composite object and on its components.
A Facade seems like it does something very similar but I think it lifts the restriction where the composite object has to conform to the same API. The whole point of a Facade is that the APIs of the wrapper and wrapped can be different.
The example you show is neither a formal Composite or Facade but if you take the most open definition of Composite, then it could be one: "an object that has other objects as members on which it performs operations."
Upvotes: 1