熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> Java編程 >> Java核心技術 >> 正文

Java設計模式-----Mediator中介者模式

2022-06-13   來源: Java核心技術 

  源自

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


From:http://tw.wingwit.com/Article/program/Java/hx/201311/26381.html
    推薦文章
    Copyright © 2005-2022 電腦知識網 Computer Knowledge   All rights reserved.