Chinaunix首页 | 论坛 | 博客
  • 博客访问: 754881
  • 博文数量: 771
  • 博客积分: 6000
  • 博客等级: 准将
  • 技术积分: 5005
  • 用 户 组: 普通用户
  • 注册时间: 2008-09-11 14:24
文章分类

全部博文(771)

文章存档

2011年(1)

2008年(770)

我的朋友

分类:

2008-09-11 14:33:03

    源自:

    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();
        }
    }

【责编:landy】

--------------------next---------------------

阅读(391) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~