课程: Programming Foundations: Design Patterns

Understanding the adapter pattern

- We just learned about the strategy pattern so you might have this idea that all design patterns are abstract and un-intuitive. Well, that's not the case. Let's look at another Gang of Four pattern, the Adapter pattern. Let's say that you need to plug an American style electrical cord into a European style outlet, well you can't, they have different interfaces. So to make this work, we use an adapter that adapts the European style outlet into the American style plug. It translates the outlets interface into one the American plug expects. From the perspective of the plug and the outlet, nothing has changed. They do what they've always done. Let's look at a more software oriented case. Let's say we're using a Vendor's class to achieve some goal and that class has it's own specific interface. At some point, you may want to use a different Vendor class. Perhaps you found one that's better, cheaper or faster. The only problem is that the new Vendor class has a different interface than your existing Vendor class, so how do you use it to make the system and the new Vendor class work together? Well, you create an Adapter class that implements the existing interface and then talks to the Vendor's class to carry out request. If we do our job right, the existing system and the new Vendor class will do what they've always done without the need for code changes. It's the Adapter class that will handle the work of translating the request to the new Vendor class.

内容