Facade vs. Adapter vs. Decorator design pattern

All are structural design patterns. Structural design patterns are good ways to define shape or structure of your code, like how your class internally structured to satisfy a need or solve a problem. In contrast to Creational patterns that give ideas about how to instantiate objects of a class, and Behavioral patterns that show possible ways to make objects of classes communicate.

Facade Pattern:

Provides simple interface. Example is a class that contains simple methods that call various methods from other complex classes. Your class here is a Facade class.

Adapter Pattern:

Converts one interface to another. Example is when you make a web API to serve a client and it consumes another API that does not match client expectation, but your API adapts it to client expectations. Your API here is an Adapter API.

Decorator Pattern:

Adds non-existing feature/behavior. Example is when you have a BankAccount class which by default doesn’t have count of withdrawal operations occurred, then you decide to inherit it by CountBankAccount class then add WithdrawCount property to get the count of withdrawal operations. Here you decorate BankAccount in CountBankAccount which is called a Decorator class, by adding a non-existing feature which is counting withdrawal operations. Another way to do that is to use an object of the decorated class inside the decorator class, which is called composition.

Now you may ask what is the difference between decoration inheritance and normal inheritance?!

Actually decoration can be done by inheritance, but not all inheritance is decoration. The kind of inheritance that adds a business feature or behavior is called business decoration, and the kind which adds a UI feature or behavior is called UI decoration. For example if you inherit Button UI class to add a nice border or custom animation, here you are decorating the button class. While in normal inheritance, you can hide features or behaviors, and can support different equivalent behaviors in equivalent classes which is called polymorphism. All of those kinds of inheritance and more cannot be considered as decoration.

Leave a comment

Create a website or blog at WordPress.com

Up ↑