18) Mediator pattern
类别:
Behavioral Pattern
问题:
encapsulate [ɪn'kæpsjʊleɪt] enclose in a capsule or other small container
define an object that encapsulates how a set of objects interact.
方案:
示例:
import java.util.ArrayList; import java.util.List; public class MediatorPatternDemo { public static void main(String[] args) { Mediator mediator = new Talkgroup(); Talker talker1 = new Person(mediator, "Pankaj"); Talker talker2 = new Person(mediator, "Lisa"); Talker talker3 = new Person(mediator, "Saurabh"); Talker talker4 = new Person(mediator, "David"); mediator.addUser(talker1); mediator.addUser(talker2); mediator.addUser(talker3); mediator.addUser(talker4); talker1.send("Hi All"); } } interface Mediator { public void sendMessage(String msg, Talker user); void addUser(Talker user); } abstract class Talker { protected Mediator mediator; protected String name; public Talker(Mediator med, String name) { this.mediator = med; this.name = name; } public abstract void send(String msg); public abstract void receive(String msg); } class Talkgroup implements Mediator { private List<Talker> TalkerList; public Talkgroup() { this.TalkerList = new ArrayList<Talker>(); } @Override public void addUser(Talker talker) { this.TalkerList.add(talker); } @Override public void sendMessage(String msg, Talker talker) { for (Talker t : this.TalkerList) { // message should not be received by the user sending it if (t != talker) { t.receive(msg); } } } } class Person extends Talker { public Person(Mediator med, String name) { super(med, name); } @Override public void send(String msg) { System.out.println(this.name + " >>>>>>> " + msg); mediator.sendMessage(msg, this); } @Override public void receive(String msg) { System.out.println(this.name + " <<<<<<<< " + msg); } }
Pankaj >>>>>>> Hi All Lisa <<<<<<<< Hi All Saurabh <<<<<<<< Hi All David <<<<<<<< Hi All
应用:
不足:(
优化:)