Is a mapper a version of the adapter pattern
Asked Answered
C

1

22

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?

Chronologist answered 8/2, 2017 at 18:31 Comment(0)
K
33

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.

Kiger answered 8/2, 2017 at 22:49 Comment(2)
Thanks its good example and it makes perfect sense, could you possibly elaborate to explain to me why you would need to do that? Instead of just option one? Is it to allow any updates to the cat to propogate through to the dog adapted object? Is it a matter of static properties vs a dynamicically updated property?Chronologist
Sometimes it's more expensive to copy the data over to support the target interface (in this case Dog is the target interface) than it is to simply translate the calls. Adaptation of a remote interface to another interface is another example where the properties may change based on backend data, you don't want to copy the attributes because that would provide a 'snapshot', not the 'current' value.Kiger

© 2022 - 2024 — McMap. All rights reserved.