Click here to watch in Youtube : https://www.youtube.com/watch?v=Sqpgv1QMIPk
Click the below Image to Enlarge
Bridge Design pattern - Implementation [Send Message] |
Bridge Design pattern - Implementation [Send Message] - Class Diagram |
MessageSender.java
public interface MessageSender
{
public void sendMessage(String message);
}
SmsMessageSender.java
public class SmsMessageSender implements MessageSender
{
public void sendMessage(String message)
{
System.out.println("'"+message+ "' : This Message has been sent using SMS");
}
}
EmailMessageSender.java
public class EmailMessageSender implements MessageSender
{
public void sendMessage(String message)
{
System.out.println("'"+message+ "' : This Message has been sent using Email");
}
}
Message.java
abstract class Message
{
protected MessageSender messageSender;
abstract public void sendMessage(String message);
}
ShortMessage.java
public class ShortMessage extends Message
{
public ShortMessage(MessageSender messageSender)
{
super.messageSender = messageSender;
}
@Override
public void sendMessage(String message)
{
if(message.length()<=5)
{
messageSender.sendMessage(message);
}
else
{
System.out.println("Sorry cannot send the message.....");
}
}
}
LongMessage.java
public class LongMessage extends Message
{
public LongMessage(MessageSender messageSender)
{
super.messageSender = messageSender;
}
@Override
public void sendMessage(String message)
{
messageSender.sendMessage(message);
}
}
Client.java
import java.util.Scanner;
public class Client
{
public static void main(String[] args)
{
System.out.println("Do you want to send 'longmessage' or 'shortmessage' ?");
Scanner scanner = new Scanner(System.in);
String messageType = scanner.next();
System.out.println("Please enter the message you want to send");
Scanner scanner1 = new Scanner(System.in);
String message = scanner1.nextLine();
if (messageType.equalsIgnoreCase("longmessage"))
{
Message longMessage = new LongMessage(new EmailMessageSender());
longMessage.sendMessage(message);
}
else
{
Message shortMessage = new ShortMessage(new SmsMessageSender());
shortMessage.sendMessage(message);
}
}
}
Output
Do you want to send 'longmessage' or 'shortmessage' ?
longmessage
Please enter the message you want to send
Hello how are you ? when did you come?
'Hello how are you ? when did you come?' : This Message has been sent using Email
Do you want to send 'longmessage' or 'shortmessage' ?
shortmessage
Please enter the message you want to send
hi
'hi' : This Message has been sent using SMS
No comments:
Post a Comment