Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is a mapper a version of the adapter pattern

I have been trying to get my head around the adapter pattern, out of all the patterns it's the hardest for me to imagine a use for it.

I think I understand what is achieved, to me it is to convert an object to another interface so a client can use it.

In the examples I have seen they make sense but I feel like I could achieve the same with a mapper that takes an object and maps it's properties (possibly applying some logic as well) to the needed object type so the real object is used instead.

Is there a difference or are they different names for the same thing?

like image 409
berimbolo Avatar asked Feb 08 '17 18:02

berimbolo


1 Answers

Think of an adapter not as a creator of new objects (like a Mapper) but as an interface translator.

Mapper m = new Mapper()
Dog dog = (Dog) m.mapRow(resultSet); // creating new object

The cat instance still exists here, a new 'dog instance' is not created, rather the DogAdapter instance is created and 'adapts' the cat object to the Dog interface.

Cat cat = new Cat("Felix");
Dog dog = new DogAdapter(cat); // cat  still exists
dog.bark(); // yields 'meow'

These are obviously contrived examples but hopefully they will help you understand better.

like image 111
Trever Shick Avatar answered Sep 22 '22 04:09

Trever Shick