Sunday, December 6, 2015

Head Fist Design Pattern CH7: Adapter and Facade Pattern and Principle of Least Knowledge

Adapter Pattern

lets say you have a Duck interface

and here is the implementation

also we have another interface which is Turkey 

as you can see in Turkey interface we have gobble() not quack.
here is the implementation.

the problem here, as WildTurkey and MallardDuck implement different interfaces you cannot use them interchangeably. 

in order to use them in a polymorphic style we should define an adapter to make the Turkey looks like Duck

the adapter looks like this

as you can see the Adapter implements the Duck interface, and it uses a Turkey instance.
the quack() method implementation is simple a call to the gobble() 

now to use the previous code

Facade Pattern
lets say that we have a home theater system 

as you can see, many classes are involved in this system, in order to watch a movie you should do all this:

which means if you want to use the system, you will make a lot of call, 

in case you have such a system, and you want to simplify the call you can define a Facade class, that simplify the call,

the Facade pattern hide all the internal complexity of a system, it is responsible for doing all the calls.

The Principle of Least Knowledge
it means that classes should not know much about each other.

in order to achieve that, each object can invoke only the following methods:

The Facade pattern is a good example of this Principle

No comments:

Post a Comment