Structural Design Patterns: Adapter Pattern
On previous blog posts we focused on creational design patterns such as the builder pattern, the abstract factory/factory pattern, the singleton and the prototype pattern.
We will switch our focus to the structural design patterns. By using structural design patterns our goal is to ease the design by identifying a simple way to realize relationships between entities.
Adapter pattern is one of the most used and well known structural patterns. Its major usage is when you want to make classes work with other classes without having to change its source code.
Imagine the scenario of refactoring some code and you stumble upon a class sending emails.
package com.gkatzioura.design.structural.adapter; import java.util.List; public class MailSender { private String title; private String message; private List<String> recipients; public MailSender(String title, String message, List<String> recipients) { this.title = title; this.message = message; this.recipients = recipients; } public void sendMessage() { } public void sendHtmlMessage(String htmlTemplate) { } }
The MailSender class has the ability to send an email but also you can use it in order to send an email containing html.
We want to add some subscribe/notify functionality in our code base so that people could receive a simple message in the form of sms, email, webhooks etc.
We have also come up with an interface for the notify functionality.
package com.gkatzioura.design.structural.adapter; public interface Notifier { void notify(String recipients,String message); }
As you can see our notify action does not really care about the subject or formatting of the message. You just have to notify the subscribes. Among the rest implementation an email implementation should be provided. We can either provide a new email implementation which implements the notifier interface or we can change the original email class.
However there is a third option. You can use the adapter pattern and create a class so that you can reuse your old email class.
By doing this you don’t alter your old email class and therefore the code which uses its functionality and also you skip creating a new class therefore having to maintain one extra class.
package com.gkatzioura.design.structural.adapter; import java.util.List; public class MailNotifierAdapter implements Notifier { private static final String NOTIFICATION_TITLE = "System notification"; public void notify(List<String> recipients, String message) { MailSender mailSender = new MailSender(NOTIFICATION_TITLE,message,recipients); mailSender.sendMessage(); } }
You can find the source code on github.
Published on Java Code Geeks with permission by Emmanouil Gkatziouras, partner at our JCG program. See the original article here: Structural Design Patterns: Adapter Pattern Opinions expressed by Java Code Geeks contributors are their own. |