Write a Notification superclass whose final send() validates the recipient, formats the message and records it, while EmailNotification and SmsNotification supply their own validation and format.
Solution
Main.java
import java.util.ArrayList;
import java.util.List;
abstract class Notification {
static final List<String> SENT = new ArrayList<>();
final String send(String to, String msg) {
if (!valid(to)) return "invalid recipient: " + to;
String out = format(to, msg);
SENT.add(out);
return out;
}
protected abstract boolean valid(String to);
protected abstract String format(String to, String msg);
}
class EmailNotification extends Notification {
@Override protected boolean valid(String to) { return to.matches("[^@\\s]+@[^@\\s]+\\.[a-z]+"); }
@Override protected String format(String to, String msg) { return "EMAIL to " + to + " | Subject: " + msg.split("\\.")[0]; }
}
class SmsNotification extends Notification {
@Override protected boolean valid(String to) { return to.matches("[6-9]\\d{9}"); }
@Override protected String format(String to, String msg) {
String text = msg.length() > 20 ? msg.substring(0, 17) + "..." : msg;
return "SMS to " + to + " | " + text;
}
}
public class Main {
public static void main(String[] args) {
Notification email = new EmailNotification(), sms = new SmsNotification();
String msg = "Your order has shipped. Track it in the app.";
System.out.println(email.send("asha@mail.com", msg));
System.out.println(email.send("asha.mail.com", msg));
System.out.println(sms.send("9876543210", msg));
System.out.println(sms.send("12345", msg));
System.out.println(Notification.SENT.size() + " sent");
}
}
Output Verified by compiling and running
EMAIL to asha@mail.com | Subject: Your order has shipped
invalid recipient: asha.mail.com
SMS to 9876543210 | Your order has sh...
invalid recipient: 12345
2 sent
The parent fixes the steps of sending (the Template Method pattern); each subclass fills in only what differs.
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!