Chinaunix首页 | 论坛 | 博客
  • 博客访问: 3476089
  • 博文数量: 1450
  • 博客积分: 11163
  • 博客等级: 上将
  • 技术积分: 11101
  • 用 户 组: 普通用户
  • 注册时间: 2005-07-25 14:40
文章分类

全部博文(1450)

文章存档

2017年(5)

2014年(2)

2013年(3)

2012年(35)

2011年(39)

2010年(88)

2009年(395)

2008年(382)

2007年(241)

2006年(246)

2005年(14)

分类: 项目管理

2009-03-30 23:11:32

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 colleagueList = new ArrayList();

        public void register(AbstractColleague ac) {
            colleagueList.add(ac);
        }

        public void ColleagueChanged(AbstractColleague ac) {
            for (int i = 0; i < colleagueList.size(); i++) {
                if (colleagueList.get(i) != ac) {
                    colleagueList.get(i).action();
                }
            }
        }
    }

    public abstract class AbstractColleague {

        private AbstractMediator med;

        public AbstractColleague(AbstractMediator mediator) {
            this.med = mediator;
        }

        public abstract void action();

        public void changed() {
            med.ColleagueChanged(this);
        }
    }

    public class ConcreteColleagueA extends AbstractColleague {

        public ConcreteColleagueA(AbstractMediator mediator) {
            super(mediator);
            mediator.register(this);
        }

        public void action() {
            System.out.println("AAAAAAAAAAAAAAA");
        }
    }

    public class ConcreteColleagueB extends AbstractColleague {

        public ConcreteColleagueB(AbstractMediator mediator) {
            super(mediator);
            mediator.register(this);
        }

        public void action() {
            System.out.println("BBBBBBBBBBBBBBB");
        }
    }

    public class ConcreteColleagueC extends AbstractColleague {

        public ConcreteColleagueC(AbstractMediator mediator) {
            super(mediator);
            mediator.register(this);
        }

        public void action() {
            System.out.println("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);
            colleagueA.changed();
            colleagueB.changed();
            colleagueC.changed();
        }
    }

阅读(647) | 评论(0) | 转发(0) |
0

上一篇:备忘录模式

下一篇:状态模式

给主人留下些什么吧!~~