Note - In the class diagram above I have focussed on showing the primary participating classes & their methods. I have not included the method parameters and constructors in the same.
Code for the classes drawn in Java Class Diagram
Code for classes shown in Java Class Diagram//FileCommiter.java import java.io.File; public class FileCommiter < String diskLocation; public FileCommiter()< //default constructor >public FileCommiter(String diskLocation) < this.diskLocation=diskLocation; >public void saveFile(File file) < //Logic for saving the file at the diskLocation goes here >> //FileEmailer.java import java.io.File; public class FileEmailer < public String emailAddress; public FileEmailer(String emailAddress)< this.emailAddress=emailAddress; >public void emailFile(File file) < //Logic for emailing the file goes here >> //FileEmailerAdapter.java import java.io.File; public class FileEmailerAdapter extends FileCommiter < public FileEmailer fileEmailer; public FileEmailerAdapter(FileEmailer fileEmailer)< this.fileEmailer=fileEmailer; >public void saveFile (File file) < this.fileEmailer.emailFile(file); >> //Client.java import java.io.File; public class Client < public static void main(String args[])< File file=new File(args[0]); FileCommiter fileCommiter=new FileCommiter("C:\\"); fileCommiter.saveFile(file);//This will save the file on the disk location C: drive //Now we want to email with the same Target class FileCommiter fileCommiter=new FileEmailerAdapter(new FileEmailer("abcd@javabrahman.com")); fileCommiter.saveFile(file);//This will email the file to abcd@javabrahman.com >>
Summary This concludes the article on adapter design pattern where we saw what is adapter pattern. Then we learned about its two variants - Class and Object Adapters and saw class diagram of each. Then we saw a Java Implementation of a FileEmailer Adapter through code and then its explanation.