美文网首页
中介者模式

中介者模式

作者: Stroman | 来源:发表于2019-01-20 17:47 被阅读11次

    有啥用

    就是把各个对象的交互放在一个公共的场所,也可以理解为第三方。就好像是房屋中介和婚姻介绍所。最典型的例子就是MVC。

    类图

    类图.png

    结果

    买家:大哥,要盘吗?
    卖家:滚!
    
    Process finished with exit code 0
    

    使用

    package com.company;
    
    public class Main {
    
        public static void main(String[] args) {
        // write your code here
            Market market = new Market();
            Solder solder = new Solder(market);
            Buyer buyer = new Buyer(market);
            market.setBuyer(buyer);
            market.setSolder(solder);
    
            solder.sendMessage("大哥,要盘吗?");
            buyer.sendMessage("滚!");
        }
    }
    
    

    抽象的中介者

    package com.company;
    
    public abstract class Mediary {
        void sendMessage(String message,Participant participant) {}
    }
    
    

    具体的中介者——市场

    package com.company;
    
    public class Market extends Mediary {
        private Participant buyer;
        private Participant solder;
    
        public void setBuyer(Participant buyer) {
            this.buyer = buyer;
        }
    
        public void setSolder(Participant solder) {
            this.solder = solder;
        }
    
        @Override
        void sendMessage(String message,Participant participant) {
            super.sendMessage(message,participant);
            if (participant == buyer) {
                System.out.println("卖家:" + message);
            } else {
                System.out.println("买家:" + message);
            }
        }
    }
    
    

    通过中介交互的各方

    package com.company;
    
    public abstract class Participant {
        protected Mediary mediary;
    
        void sendMessage(String message) {}
    }
    
    

    卖方

    package com.company;
    
    public class Solder extends Participant {
        public Solder(Mediary mediary) {
            this.mediary = mediary;
        }
    
        @Override
        void sendMessage(String message) {
            super.sendMessage(message);
            this.mediary.sendMessage(message,this);
        }
    }
    
    

    买家

    package com.company;
    
    public class Buyer extends Participant {
        public Buyer(Mediary mediary) {
            this.mediary = mediary;
        }
    
        @Override
        void sendMessage(String message) {
            super.sendMessage(message);
            this.mediary.sendMessage(message,this);
        }
    }
    
    

    多谢捧场

    如果您觉得我的文章有价值,那么赏脸打赏一个,鄙人感激不尽。不过,不打赏看看也是好的,如果有不对的地方,还请您多多指正。


    相关文章

      网友评论

          本文标题:中介者模式

          本文链接:https://www.haomeiwen.com/subject/egzxjqtx.html