Sunday, 26 January 2014

Bridge Design pattern - Implementation [Publish Message]

Master Software Architecture & Clean Code!

Subscribe to Ram N Java for clean code, design pattern implementations, and practical Java tutorials!

SUBSCRIBE NOW

What is the Bridge Design Pattern?

The Bridge Design Pattern decouples an abstraction from its implementation so that both can evolve independently. Instead of relying on rigid, multi-level class inheritance—which causes an explosion of subclasses—the Bridge pattern connects separate class hierarchies through composition.

In a message publishing or notification system, the type of message being processed (e.g., text, encrypted, or urgent) acts as the abstraction, while the delivery platform (e.g., Email, SMS, or Push Notification) serves as the concrete implementation.

Complete Java Code Implementation

Below is a clean, practical Java implementation illustrating the Bridge pattern with a real-world message publishing architecture:

// 1. Implementor Interface
interface MessageSender {
    void sendMessage(String message);
}

// 2. Concrete Implementors
class EmailSender implements MessageSender {
    @Override
    public void sendMessage(String message) {
        System.out.println("Email: Sending message -> " + message);
    }
}

class SmsSender implements MessageSender {
    @Override
    public void sendMessage(String message) {
        System.out.println("SMS: Sending text -> " + message);
    }
}

// 3. Abstraction (Bridge holding the Implementor reference)
abstract class Message {
    protected MessageSender messageSender;

    public Message(MessageSender messageSender) {
        this.messageSender = messageSender;
    }

    public abstract void publish(String content);
}

// 4. Refined Abstractions
class TextMessage extends Message {
    public TextMessage(MessageSender messageSender) {
        super(messageSender);
    }

    @Override
    public void publish(String content) {
        messageSender.sendMessage("[Standard Text] " + content);
    }
}

class EncryptedMessage extends Message {
    public EncryptedMessage(MessageSender messageSender) {
        super(messageSender);
    }

    @Override
    public void publish(String content) {
        String encryptedContent = new StringBuilder(content).reverse().toString();
        messageSender.sendMessage("[Encrypted] " + encryptedContent);
    }
}

// 5. Client Application
public class BridgePatternDemo {
    public static void main(String[] args) {
        // Send a text message via Email
        Message emailMessage = new TextMessage(new EmailSender());
        emailMessage.publish("Welcome to Ram N Java!");

        // Send an encrypted message via SMS
        Message smsMessage = new EncryptedMessage(new SmsSender());
        smsMessage.publish("TopSecretCode123");

        // Swap channels dynamically: Send encrypted content via Email
        Message secureEmail = new EncryptedMessage(new EmailSender());
        secureEmail.publish("ConfidentialReport2026");
    }
}

Key Architectural Advantages

  • Prevents Combinatorial Subclass Explosion: Adding 3 message types and 3 delivery channels creates only 6 classes instead of 9 tightly coupled variants.
  • Runtime Channel Switching: Delivery mechanisms can be injected dynamically at runtime based on configuration or user preferences.
  • Open/Closed Principle: You can add a new messaging format or a new transport channel without modifying existing classes.

Watch More Related Design Pattern Tutorials


Click here to watch in Youtube : https://www.youtube.com/watch?v=Q2L3FGnjPu0

Click the below Image to Enlarge

Bridge Design pattern - Implementation [Publish Message]

Bridge Design pattern - Implementation [Publish Message] - Class Diagram


MessagePublisher.java

public interface MessagePublisher
{
public void publishMessage(String message);
}


Facebook.java

public class Facebook implements MessagePublisher
{

public void publishMessage(String message)
{
System.out.println("'"+message+ "' : This message has been published to public in Facebook Social networking site");
}
}

Twitter.java

public class Twitter implements MessagePublisher
{

public void publishMessage(String message)
{
System.out.println("'"+message+ "' : This message has been published to public in Twitter Social networking site");
}
}

GooglePlus.java

public class GooglePlus implements MessagePublisher
{

public void publishMessage(String message)
{
System.out.println("'"+message+ "' : This message has been published to public in GooglePlus Social networking site");
}
}


Message.java

abstract class Message
{

protected MessagePublisher messagePublisher;

protected MessagePublisher getMessagePublisher()
{
return messagePublisher;
}

protected void setMessagePublisher( MessagePublisher messagePublisher )
{
this.messagePublisher = messagePublisher;
}

abstract public void publishMessage(String message);

}

LongMessage.java

public class LongMessage extends Message
{

@Override
public void publishMessage( String message )
{
messagePublisher.publishMessage(message);
}

}

ShortMessage.java

public class ShortMessage extends Message
{

private static int MESSAGE_LENGTH = 200;

@Override
public void publishMessage( String message )
{
if( message.length() <= MESSAGE_LENGTH )
{
messagePublisher.publishMessage(message);
}
else
{
System.out.println("Sorry message length is more cann't publish.....");
}

}

}


Client.java

import java.util.Scanner;

public class Client
{

public static void main( String[] args )
{

System.out.println("Please enter the Social networking site you want to use to publish the message  : 'Twitter' or 'Facebook' or 'GooglePlus'");
Scanner scanner = new Scanner(System.in);
String socialNetworkingSite = scanner.next();
System.out.println("Please enter the message you want to publish");
Scanner scanner1 = new Scanner(System.in);
String message = scanner1.nextLine();

if( "Twitter".equalsIgnoreCase(socialNetworkingSite) )
{
ShortMessage shortMessage = new ShortMessage();
shortMessage.setMessagePublisher(new Twitter());
shortMessage.publishMessage(message);
}
else if( "Facebook".equalsIgnoreCase(socialNetworkingSite) )
{
LongMessage longMessage = new LongMessage();
longMessage.setMessagePublisher(new Facebook());
longMessage.publishMessage(message);
}
else if( "GooglePlus".equalsIgnoreCase(socialNetworkingSite) )
{
LongMessage longMessage = new LongMessage();
longMessage.setMessagePublisher(new GooglePlus());
longMessage.publishMessage(message);
}

}
}


Output

Please enter the Social networking site you want to use to publish the message  : 'Twitter' or 'Facebook' or 'GooglePlus'
Twitter
Please enter the message you want to publish
hello
'hello' : This message has been published to public in Twitter Social networking site


Please enter the Social networking site you want to use to publish the message  : 'Twitter' or 'Facebook' or 'GooglePlus'
Facebook
Please enter the message you want to publish
hello bow are you?
'hello bow are you?' : This message has been published to public in Facebook Social networking site

See also:

  • Bridge Design pattern - Introduction
  • Bridge Design pattern - Real time example [Send Message]
  • Bridge Design pattern - Real time example [Publish Message]
  • Bridge Design pattern - Real time example [Shape]
  • Bridge Design pattern - Real time example [TV]
  • Bridge Design pattern - Class Diagram
  • Bridge Design pattern - Implementation [Shape]
  • Bridge Design pattern - Implementation [Send Message]
  • Bridge Design pattern - Implementation [LED TV]
  • Bridge Design pattern - Keypoints
  • All Design Patterns Links
  • No comments:

    Post a Comment

    Tutorials