这个模式一直没有好好的理解。最近作IM 相关的应用,才明白了。
就是两个人之间要沟通,不是直接,而是通过 mediator.
也就是 ,不是
user1.sendMessage(user2,"some message");
而是
user1.getMediator().sendMessage("user2","some message");
有什么好处呢:
职责分离:mediator 完成自己该承担的职责。
mediator 也可以搞这搞那。
插一段实际代码:
conn.getChatManager().createChat("thewho@stephenli",new MessageListener() {
public void processMessage(Chat chat, Message message) {
if(logger.isDebugEnabled())
logger.debug("Received message: " + message.toXML());
}
}).sendMessage("测试发送!");
下面是junit 一段别人的代码,可以Run:
代码看起来很蠢,不能说明使用mediator 的好处。不过意思就是这样啦!(从C# 拷的)
import junit.framework.TestCase;
public class MediatorTest extends TestCase {
public void testMediator(){
Mediator m = new Mediator();
DataProviderColleague c1 = new DataProviderColleague(m);
DataConsumerColleague c2 = new DataConsumerColleague();
m.IntroduceColleagues(c1,c2);
c1.ChangeData();
}
}
class Mediator
{
private DataProviderColleague dataProvider;
private DataConsumerColleague dataConsumer;
public void IntroduceColleagues(DataProviderColleague c1, DataConsumerColleague c2)
{
dataProvider = c1;
dataConsumer = c2;
}
public void DataChanged()
{
int i = dataProvider.getIMyData();
dataConsumer.NewValue(i);
}
}
class DataConsumerColleague
{
public void NewValue(int i)
{
System.out.println("New value "+ i);
}
}
class DataProviderColleague
{
private Mediator mediator;
private int iMyData=0;
private int MyData ;
public DataProviderColleague(Mediator m)
{
mediator = m;
}
public void ChangeData()
{
iMyData = 403;
// Inform mediator that I have changed the data
if (mediator != null)
mediator.DataChanged();
}
public int getIMyData() {
return iMyData;
}
public void setIMyData(int myData) {
iMyData = myData;
}
}
西津渡