java

位置:IT落伍者 >> java >> 浏览文章

Java设计模式-----Mediator中介者模式


发布日期:2021年07月04日
 
Java设计模式-----Mediator中介者模式

源自

Mediator中介者模式

用一个中介者对象来封装一系列的对象交互中介者使各对象不需要显式的相互引用从而使其耦合松散而且可以独立的改变他们之间的交互

例子

view plaincopy to clipboardprint?

public abstract class AbstractMediator {

public abstract void register(AbstractColleague ac);

public abstract void ColleagueChanged(AbstractColleague ac);

}

public class ConcreteMediator extends AbstractMediator {

private ArrayList<ABSTRACTCOLLEAGUE></ABSTRACTCOLLEAGUE> colleagueList = new ArrayList<ABSTRACTCOLLEAGUE></ABSTRACTCOLLEAGUE>();

public void register(AbstractColleague ac) {

colleagueListadd(ac);

}

public void ColleagueChanged(AbstractColleague ac) {

for (int i = ; i < colleagueListsize(); i++) {

if (colleagueListget(i) != ac) {

colleagueListget(i)action();

}

}

}

}

public abstract class AbstractColleague {

private AbstractMediator med;

public AbstractColleague(AbstractMediator mediator) {

d = mediator;

}

public abstract void action();

public void changed() {

medColleagueChanged(this);

}

}

public class ConcreteColleagueA extends AbstractColleague {

public ConcreteColleagueA(AbstractMediator mediator) {

super(mediator);

mediatorregister(this);

}

public void action() {

Systemoutprintln(AAAAAAAAAAAAAAA);

}

}

public class ConcreteColleagueB extends AbstractColleague {

public ConcreteColleagueB(AbstractMediator mediator) {

super(mediator);

mediatorregister(this);

}

public void action() {

Systemoutprintln(BBBBBBBBBBBBBBB);

}

}

public class ConcreteColleagueC extends AbstractColleague {

public ConcreteColleagueC(AbstractMediator mediator) {

super(mediator);

mediatorregister(this);

}

public void action() {

Systemoutprintln(CCCCCCCCCCCCCCC);

}

}

public class Client {

public static void main(String[] args) {

AbstractMediator mediator = new ConcreteMediator();

AbstractColleague colleagueA = new ConcreteColleagueA(mediator);

AbstractColleague colleagueB = new ConcreteColleagueB(mediator);

AbstractColleague colleagueC = new ConcreteColleagueC(mediator);

colleagueAchanged();

colleagueBchanged();

colleagueCchanged();

}

}

               

上一篇:Java网络编程从入门到精通(18):Socket类的getter和setter方法(2)

下一篇:JAVA如何实现从最后一行读取文件