Suppose we have an HR system that uses a Billing System, e.g. a client of HR system wants full details of an employee, including salary. However, HR system doesn’t have salary information stored in its database and needs to call billing system to get employee’s salary. So the HR system calls
int getSalary(String employeeName, String employeePesel) on the reference defined by Billing System interface.
Now suppose, that HR system wants to change the billing system to the 3rd party implementation, that has a different interface method to obtain employee payment:
Payment getPersonPayment(Person person).
So we need to adapt HR system to the new Billing system interface. However, we don’t want to change HR system implementation.
The solution is the following:
In the current code, HR system sets the implementation of Billing system via constructor or setter method. So we can set the implementation of the adapted 3rd party Billing System as long the adapted version matches the old billing system interface. The solution is to create an adapter class that implements this old billing system interface but internally the call to each overrided method will be delegated to the new 3rd party interface.
Draft: We have a class that doesn’t apply to our target interface. We need to wrap our class with a new adapter class that implements the target interface and has a member variable of type of our class and sets it via constructor/setter. The call to the adapter class method is delegated internally to our class method call.
Suppose you change your 3rd party library, that has different interface than previous. You can’t change vendor’s interface and you don’t want to change your existing code.
Wrapping an object
When an object A is said to “Wrap” object B it means that Object A HAS A reference to the Object B and deligates calls to it.
Putting an object as an member variable of another object(say domain object) for providing more functionality or for business purpose is called wrapping an object. Example: wrapper classes that wraps primitive types such that primitive type values can be treated as objects.
“Wrapping” an object means that a number of methods on an object defer control to another method hidden behind a private field.