Soruce : ht tp://wimpi.coalevo.net/2007/09/osgi-design-practice-loose-coupling.html
Mediator 的class diagram:
Mediator這個Pattern主要在解決交錯複雜的關係,常常我們程式會有一些複雜的關係存在,若彼此都互相緊密關聯,Mediator就扮演一個中介的角色,所有人只跟Mediator溝通,Mediator負責收集所有狀態的改變,並且通知所有需要牽動的人。Mediator 有點 Facade 和 Observer 的感覺, Mediator 就像是個 Observer ,每個元件都會把 Mediator 註冊到自己本身身上,當本身有變化時,就利用已註冊在自己身上的 Mediator 去通知自己已經變化了。
看了幾個Sample 之後, 發現最多的例子都是拿一個Swing 的元件, 比如說小算盤這種元件來當例子,
最簡單的實作就是
Mediator Interface
public interface Mediator { public void register(String name, Colleague c); public void call(String name, Colleague from); }
Mediator Implements
public class ConcreteMediator implements Mediator{ private Hashtable<String, Colleague> colleagues = new Hashtable<String, Colleague>(); public void register(String name, Colleague c) { colleagues.put(name, c); } public void call(String name, Colleague from) { Colleague c = colleagues.get(name); if(c!=null){ System.out.println(from.getName() + " call " + c.getName()); } } }
Interface colleague
public interface Colleague { public void call(String name); public String getName(); }
Colleague Implements 1
public class ConcreteColleague1 implements Colleague { private String name = "aa"; private Mediator med; public ConcreteColleague1(Mediator med){ this.med = med; this.med.register(this.name, this); } public String getName(){ return this.name; } public void call(String name) { this.med.call(name, this); } }
Colleague Implements 2
public class ConcreteColleague2 implements Colleague { private String name = "bb"; private Mediator med; public ConcreteColleague2(Mediator med){ this.med = med; this.med.register(this.name, this); } public String getName(){ return this.name; } public void call(String name) { this.med.call(name, this); } }
Example Reference:
Wiki : http://en.wikipedia.org/wiki/Mediator_pattern
http://smartlife.blog.51cto.com/1146871/277270
http://caterpillar.onlyfun.net/Gossip/DesignPattern/MediatorPattern.htm
http://humank.wordpress.com/2011/04/19/gof-behavioral-mediator-pattern/
http://chenjumin.iteye.com/blog/640853
沒有留言:
張貼留言