Today i'm gonna show the Adapter design pattern in action. The Adapter design pattern is a very useful programming design pattern whenever you need to ensure communication between incompatible interfaces, classes or objects.
I'm assuming here you already know the concepts and i'll be focusing on practise. The example i will provide is a nice way to show it how it could looks like. You can always come back here, take it, adapt it and use it in your applictions as you may need. So be sure you bookmark it or join the group here on the right side of this post subscribing it.
First of all, let's take a look at the UML diagram of it. After that we will take the analogy for our example.
The UML Diagram of the Adapter Pattern
Pay close attention, because once you understand that, everything will become clear and simple to understand. That's the reason I'm putting always the UML first. That way you'll get an eye for it with the time.
The example
In our example we will see, how we could adapt incompatible interfaces so that they can interact together. We will connect a rounded 3-pins plug with a rectangular 2-pins plug.Incompatible Classes
The classes to adapt.public class CylinderSocket { public CylinderPin cylinderPin; public CylinderSocket(){ this.cylinderPin=new CylinderPin("corrent", "neutro", "terra"); } } public class RectangularPlug {//ADAPTEE public String corrente; public String neutro; public String getPower() { return "power on!"; } }
The Adapter
To be able to adapt something, first of all we must define the common interface between at least two classes/objects.public interface Plugable { // "TARGET" INTERFACE public String getPower(); }
The Test
Finally, let's test our adapter which will connect a rounded plug with a rectangular plug.public class Client { public static void main(String[] args) { // Rounded plug with 3 pins with rectangular plug with 2 pins CylinderSocket cylinderSocket = new CylinderSocket(); // Client knows only the interface Plugable plugable = new PlugAdapter(cylinderSocket); // see if connection works System.out.println(plugable.getPower()); } }
That's all! Hope you like it!
😱👇 PROMOTIONAL DISCOUNT: BOOKS AND IPODS PRO 😱👇
Be sure to read, it will change your life!
Show your work by Austin Kleon: https://amzn.to/34NVmwx
This book is a must read - it will put you in another level! (Expert)
Agile Software Development, Principles, Patterns, and Practices: https://amzn.to/30WQSm2
Write cleaner code and stand out!
Clean Code - A Handbook of Agile Software Craftsmanship: https://amzn.to/33RvaSv
This book is very practical, straightforward and to the point! Worth every penny!
Kotlin for Android App Development (Developer's Library): https://amzn.to/33VZ6gp
Needless to say, these are top right?
Apple AirPods Pro: https://amzn.to/2GOICxy
😱👆 PROMOTIONAL DISCOUNT: BOOKS AND IPODS PRO 😱👆