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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With