34

I have been reading about design patterns and this got me curious:

Decorator Pattern says wrap an original object and add additional features in the wrapper object. So structurally speaking - Wrappers follow decorator pattern.

Adapter pattern says changing one object by creating an instance of it and adding functionalities to it. These functionalities do not match those of the original object so we have to modify them, but we may also add our own extra methods which are not a part of the original object.

In this regard, what is the difference between Adapter and Decorator design pattern?

Navin Israni
  • 1,327
  • 3
  • 15
  • 27

2 Answers2

30

Decorator, attach additional responsibilities to an object dynamically. For example adding sugar in a coffee.

Adapter, adapts interface of an existing class to another interface. For example eletrical adapter.

dstar55
  • 938
  • 6
  • 11
28

From This Answer: How do the Proxy, Decorator, Adapter, and Bridge Patterns differ?

Decorator is also called "Smart Proxy." This is used when you want to add functionality to an object, but not by extending that object's type. This allows you to do so at runtime.

Adapter is used when you have an abstract interface, and you want to map that interface to another object which has similar functional role, but a different interface.

Main difference is:

Decorator is used to decorate individual objects at run-time. Adapter is used to add features to the class and therefore to ALL of its objects.

Community
  • 1
  • 1
Navin Israni
  • 1,327
  • 3
  • 15
  • 27
  • 9
    It's true that Adapter targets the class and therefore to ALL of its objects. However, the intent of Adapter is NOT to add feature, but to convert old feature to a new interface. – Hung Thai Mar 06 '19 at 08:10
  • Both adaptor and decorator operate on _individual instances_ of the target class and apply to _any_ (therefore all) instances. You can't apply an adaptor to a class, you apply it to instances of a class, just like decorator. The difference is that decorator doesn't alter the interface of the target class. Decorator: foo() {return this.other.foo();} vs Adaptor: bar() {return this.other.foo();}. Or: decorator is dressing someone up as somebody else; adaptor is dressing someone up as a horse. – barneypitt Sep 22 '22 at 20:42