elzoy
elzoy

Reputation: 5445

Composition vs facade pattern

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

Answers (2)

tallseth
tallseth

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:

  • File.Copy() can't be easily mocked in .NET, so I write a facade that delegates to it with a virtual method, so I can mock that facade.
  • When using a 3rd party library, you may not want to allow coupling to the types in that library, so you write a facade to encapsulate those types, and only expose your copies
  • A class you want to use may have a huge number of methods, but you only need a few. A facade can be written over those few to provide a simpler interface.
  • A service class may have arcane usage ("pass in -19438 as the second argument when you want anti-aliasing enabled") that you don't need to have all the options for in your code. Create an easier to use Facade over this class to increase the readability of your core code.

Upvotes: 0

Alper
Alper

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

Related Questions