public interface Mediator{ public abstract void publishMessage(User sender, String message, User receiver); public abstract void addUser(User receiver); }
MediatorImpl.java
기존 객체간의 행동들을 Mediator에 만들어준다. User들 끼리의 소통에서 Mediator를 거쳐서 쌍방향으로 사용할 수 있게 만들어줍니다..
import java.util.*; public class MediatorImpl implements Mediator{ ArrayList<User> favorites = new ArrayList<User>(); public void publishMessage(User sender, String message, User receiver){ if(receiver != null) System.out.println("발신인 "+ sender.name +" 내용: "+message + " 수신인: "+receiver.name); else{ Iterator it = favorites.iterator(); while(it.hasNext()){ User user = (User)it.next(); if(user != sender) sender.sendMessage(message, user); } } } public void addUser(User receiver){ favorites.add(receiver); } }
User.java
public class User{ String name; Mediator mediator; public User(String name, Mediator mediator){ this.name = name; this.mediator = mediator; mediator.addUser(this); }
public void sendMessage(String message, User receiver){ mediator.publishMessage(this, message, receiver); } }
Main.java
public class Main{ public static void main(String[] args){ Mediator mediator = new MediatorImpl(); User minsoo = new User("MinSoo", mediator); User jihoon = new User("JiHoon", mediator); User sanghoon = new User("SangHoon", mediator); minsoo.sendMessage("안녕 상훈아!!", sanghoon); minsoo.sendMessage("단체 공지: 금일 7시에 회의가 있겠습니다.", null); } }