Thursday 26 December 2013

Mediator Design pattern - Implementation [Chat Room]



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

Click the below Image to Enlarge
Mediator Design pattern - Implementation [Chat Room]


Mediator Design pattern - Implementation [Chat Room]

























ChatMediator.java


public interface ChatMediator
{
public void sendMessage(String message, User user);

public void addUser(User user);
}

ChatMediatorImpl.java

import java.util.ArrayList;
import java.util.List;

public class ChatMediatorImpl implements ChatMediator
{

private List<User> users;

public ChatMediatorImpl()
{
this.users = new ArrayList<User>();
}

@Override
public void addUser( User user )
{
this.users.add(user);
}

@Override
public void sendMessage( String message, User user )
{
for( User u : this.users )
{
// Message should not be received by the user who is sending it
if( u != user )
{
u.receive(message);
}
}
}

}

User.java

public abstract class User
{
protected ChatMediator chatMediator;
protected String       name;

public User( ChatMediator chatMediator, String name )
{
this.chatMediator = chatMediator;
this.name = name;
}

public abstract void send( String message );

public abstract void receive( String message );
}


UserImpl.java

public class UserImpl extends User
{

public UserImpl( ChatMediator chatMediator, String name )
{
super(chatMediator, name);
}

@Override
public void send( String message )
{
System.out.println(this.name + ": Sending Message=" + message+"\n");
chatMediator.sendMessage(message, this);
}

@Override
public void receive( String message )
{
System.out.println(this.name + ": Received Message:" + message);
}

}

ChatClient.java

public class ChatClient
{

public static void main( String[] args )
{
ChatMediator chatMediator = new ChatMediatorImpl();
User ram = new UserImpl(chatMediator, "Ram");
User david = new UserImpl(chatMediator, "David");
User juli = new UserImpl(chatMediator, "Juli");
User steve = new UserImpl(chatMediator, "Steve");

chatMediator.addUser(ram);
chatMediator.addUser(david);
chatMediator.addUser(juli);
chatMediator.addUser(steve);

steve.send("Hello Everybody...Shall we start the meeting?");

}

}


Output

Steve: Sending Message=Hello Everybody...Shall we start the meeting?

Ram: Received Message:Hello Everybody...Shall we start the meeting?
David: Received Message:Hello Everybody...Shall we start the meeting?
Juli: Received Message:Hello Everybody...Shall we start the meeting?

See also:

  • Mediator Design pattern - Introduction
  • Mediator Design pattern - When to Use
  • Mediator Design pattern - Real Time Example [Facebook]
  • Mediator Design pattern - Real Time Example [ATC]
  • Mediator Design pattern - Real Time Example [Chat Room]
  • Mediator Design pattern - Class Diagram
  • Mediator Design pattern - Implementation [Facebook]
  • Mediator Design pattern - KeyPoints
  • All Design Patterns Links
  • No comments:

    Post a Comment