Today I will be discussing the adapter design pattern. According to a blog by journaldev.com, the adapter pattern is a design that is used to make two unrelated interfaces work together. The example used in the blog by journaldev.com refers to phone chargers and sockets. In this example, a phone battery needs 3V to charge, and the wall socket can either be 120V or 240V. So how do we take either 120V or 240V and convert it to 3V to charge the phone battery? The article suggests using an adapter, which would be the phone charger. In this example, the two interfaces are 120V and 240V, while the adapter interface is the phone charger. I feel it is important to note that according to the article, there are two approaches to the adapter pattern; object adapter and class adapter. The object adapter uses Java composition to adapt and the class adapter uses Java inheritance to adapt. However, the article points out that both approaches will result in the same conclusion. For this article, I want to focus on the class adapter approach.
The class adapter implements a public Class called SocketClassAdapterImp, and it extends the Socket interfaces and implements the SocketAdapter. This Class contains methods to override the different voltages using get() methods, and within the get methods it will convert the voltages supplied to the correct voltage, and return the converted voltage. The test class will check to see if the conversions were done correctly; that being if the test class calls for Volt v3 = getVolt(socketAdapter, 3);, it should return the correct voltage (3).
I chose this article because I wanted to expand on my knowledge of different design patterns, and this one seems to be rather important (especially since I didn’t know anything about it). I learned a lot from this article. I have never run into a situation where I have needed two different interfaces to communicate and work together. I think that this is a great approach, and it seems to be rather simple and straightforward. I learned that in order to “link” two different interfaces together, that all I need to do is create an adapter for them, which will provide some sort of conversion method to satisfy the subclass. I hope to implement this in my future works, should I run into a situation where this is applicable. I definitely think it will save a lot of space, time, and headache.
Here’s the link: https://www.journaldev.com/1487/adapter-design-pattern-java