設計模式之中介者模式

mediator

這裏寫圖片描述

結構圖

這裏寫圖片描述

實現代碼

//同事類的接口
public interface Department {
    void selfAction(); //做本部門的事情
    void outAction();  //向總經理髮出申請
}
public class Development implements Department {

    private Mediator m;  //持有中介者(總經理)的引用

    public Development(Mediator m) {
        super();
        this.m = m;
        m.register("development", this);
    }

    @Override
    public void outAction() {
        System.out.println("彙報工作!沒錢了,需要資金支持!");
    }

    @Override
    public void selfAction() {
        System.out.println("專心科研,開發項目!");
    }

}
public class Finacial implements Department {

    private Mediator m;  //持有中介者(總經理)的引用

    public Finacial(Mediator m) {
        super();
        this.m = m;
        m.register("finacial", this);
    }

    @Override
    public void outAction() {
        System.out.println("彙報工作!沒錢了,錢太多了!怎麼花?");
    }

    @Override
    public void selfAction() {
        System.out.println("數錢!");
    }

}
public class Market implements Department {

    private Mediator m;  //持有中介者(總經理)的引用

    public Market(Mediator m) {
        super();
        this.m = m;
        m.register("market", this);
    }

    @Override
    public void outAction() {
        System.out.println("彙報工作!項目承接的進度,需要資金支持!");

        m.command("finacial");

    }

    @Override
    public void selfAction() {
        System.out.println("跑去接項目!");
    }

}
//中介者
public interface Mediator {

    void register(String dname,Department d);

    void command(String dname);

}
//實現中介者接口的經理類
public class President implements Mediator {

    private Map<String,Department> map = new HashMap<String , Department>();

    @Override
    public void command(String dname) {
        map.get(dname).selfAction();
    }

    @Override
    public void register(String dname, Department d) {
        map.put(dname, d);
    }

}

public class Client {
    public static void main(String[] args) {
        Mediator m = new President();

        Market   market = new Market(m);
        Development devp = new Development(m);
        Finacial f = new Finacial(m);

        market.selfAction();
        market.outAction();

    }
}

這裏寫圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章