设计模式之Mediator(中介者)这样理解 对吗?

07-02-09 bojava
设计模式初学者!向大家请教了!

最近在看BAND老师的设计模式,看了设计模式之Mediator(中介者)这个文章,中介者,自己写了个简单的例子,这个例子主要是为了理解这个设计模式,同时,想请教一下大家如何提高设计能力!我这个代码可以如何改进,期待大家的指正!谢谢!

代码如下: 

package org.behavior.mediator;

public interface Mediator {

public void register(Colleague c);//其它人要同中介联系,注册自己

}

package org.behavior.mediator;

public class Colleague {

protected Mediator mediator;

public Mediator getMediator() {

return mediator;

}

public void setMediator(Mediator mediator) {

this.mediator = mediator;

this.mediator.register(this);

}

}

//一个买票的中介,一票难求

package org.behavior.mediator;

import java.util.ArrayList;

public class TicketMediator implements Mediator {

//member list 这个变量放在这不太合适?

ArrayList memberList;

ArrayList ticketList;

public TicketMediator() {

memberList = new ArrayList();

ticketList = new ArrayList();

}

public void register(Colleague c) {

memberList.add(c);

}

public synchronized String buyTicket() {

if (ticketList.size() > 0) {

return (String) ticketList.remove(ticketList.size() - 1);

}

return "";

}

public synchronized void sellTicket(String ticket) {

ticketList.add(ticket);

}

}

//我是卖票的,NB

package org.behavior.mediator;

public class ConcreteColleagueSeller extends Colleague {

public void sell()

{

((TicketMediator) this.mediator).sellTicket("bj-sh");

}

public String toString() {

return "ConcreteColleagueSeller";

}

}

//我要回家

package org.behavior.mediator;

public class ConcreteColleagueBuyer extends Colleague {

public void buy() {

String ticket = ((TicketMediator) this.mediator).buyTicket();

if ("".equals(ticket)) {

System.out.println("sorry!");

} else {

System.out.println("Lucky One! < "+ticket+" >");

}

}

public String toString() {

return "ConcreteColleagueBuyer";

}

}

欢迎拍砖啊!谢谢

猜你喜欢