設計模式之Mediator(中介者)這樣理解 對嗎?

bojava發表於2007-02-09
設計模式初學者!向大家請教了!
最近在看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";
}
}


歡迎拍磚啊!謝謝

相關文章