标签:
中介者模式:为了减小各个对象的直接接触,引入中介对象来对各个对象之间的复杂操作进行处理。
就像卖方中介一样的。帮助维护租客和房东之间的沟通。
示例说明:房屋买卖中介。卖房者和买房者都认识中介,但是买房者和卖房者是不认识的。
定义一个中介(单例实现)
package com.zpj.designMode.MediatorPattern; import java.util.ArrayList; import java.util.List; public class Mediator { List<Operator> opers = new ArrayList<Operator>(); public void addOperators(Operator oper) { opers.add(oper); } private static Mediator mediator = new Mediator(); private Mediator() { } public static Mediator getInstance() { return mediator; } public void sell(Operator oper, int price) { System.out.println("---------出售:" + price + "$"); for (int i = 0; i < opers.size(); i++) { Operator op = opers.get(i); if (oper != op) { if (op.topPrice > price) { op.buy(); } } } } }
定义一个炒房者抽象类Operator
package com.zpj.designMode.MediatorPattern; public abstract class Operator { protected Mediator mediator = Mediator.getInstance(); protected int topPrice = 0; public Operator(int topPrice) { super(); this.topPrice = topPrice; } public abstract void sell(int price); public abstract void buy(); }
添加两个炒房者实例:
package com.zpj.designMode.MediatorPattern; public class Operator01 extends Operator { public Operator01(int basePrice) { super(basePrice); } @Override public void sell(int price) { mediator.sell(this, price); } @Override public void buy() { System.out.println("Operator01-----------我买!"); } } package com.zpj.designMode.MediatorPattern; public class Operator02 extends Operator { public Operator02(int basePrice) { super(basePrice); } @Override public void sell(int price) { mediator.sell(this,price); } @Override public void buy() { System.out.println("Operator02-----------我买!"); } }
使用示例:
package com.zpj.designMode.MediatorPattern; import org.junit.Test; public class TestUnit { @Test public void test01() { Mediator mediator = Mediator.getInstance(); Operator op01 = new Operator01(12); Operator op02 = new Operator02(20); mediator.addOperators(op01); mediator.addOperators(op02); // 02卖方 op02.sell(1); } }
需要注意的是,operator可以互相不认识,但是Mediator 和每个operator之间是认识的。
----------------------
标签:
原文地址:http://www.cnblogs.com/PerkinsZhu/p/5843186.html