zoukankan      html  css  js  c++  java
  • java 之 中介模式(大话设计模式)

    中介模式,笔者使用比较多的是在线聊天,或者商家和客户在线沟通,正常我们首先想到的实现方式是

    客户→商家;商家→客户,这样的模式就耦合了客户和商家的关系,我们不能够轻易的改动商家或者客户。

    而中介模式的出现使得原型变成

    客户→平台→商家;商家→平台→客户。这样商家类和客户类就不会耦合在一起。另外如果商家和客户发生冲突。

    平台站在中间的立场,可以公平的解决问题

    先看下类图

    大话设计模式-类图

    在简单看下笔者的demo

    /**
     * 抽象父类人
     */
    public abstract class Person {
    
        private IMatchmaker matchmaker;
    
        public Person(IMatchmaker matchmaker) {
            this.matchmaker = matchmaker;
        }
    
        public void sendMessage(String message, Person person) {
            matchmaker.handleMessage(message, person);
        }
    
        public void receiveMessage(String message) {
            System.out.println(message);
        }
    }
    /**
     * 中介接口
     */
    public interface IMatchmaker {
    
        public void handleMessage(String message, Person person);
    }
    /**
     * 男孩
     */
    public class Boy extends Person{
    
        public Boy(IMatchmaker matchmaker) {
            super(matchmaker);
        }
    }
    /**
     * 女孩
     */
    public class Girl extends Person{
    
        public Girl(IMatchmaker matchmaker) {
            super(matchmaker);
        }
    
    }
    /**
     * 具体媒婆
     */
    public class WomanMatchmaker implements IMatchmaker{
    
        private Person person1;
    
        private Person person2;
    
        @Override
        public void handleMessage(String message, Person person) {
            if (person1.equals(person)) {
                person2.receiveMessage(message);
            } else {
                person1.receiveMessage(message);
            }
        }
    
        public Person getPerson1() {
            return person1;
        }
    
        public void setPerson1(Person person1) {
            this.person1 = person1;
        }
    
        public Person getPerson2() {
            return person2;
        }
    
        public void setPerson2(Person person2) {
            this.person2 = person2;
        }
    }
    /**
     * 客户端
     */
    public class Test {
    
        public static void main(String[] args) {
            WomanMatchmaker matchmaker = new WomanMatchmaker();
            Person person1 = new Boy(matchmaker);
            Person person2 = new Girl(matchmaker);
            matchmaker.setPerson1(person1);
            matchmaker.setPerson2(person2);
            person1.sendMessage("男:我喜欢你", person1);
            person2.sendMessage("女:我知道", person2);
        }
    }

    输出结果:

    男:我喜欢你
    女:我知道

    以上是笔者对中介模式的理解,希望能帮助学习中介模式的小伙伴。

  • 相关阅读:
    SAP应用界面开发:1)SELECTOPTIONS对象
    ABAP工作区,内表,标题行的定义和区别
    Open SQL:6)Open SQL 增刪查改(CRUD)
    SAP应用界面开发:2)PARAMETERS对象
    Open SQL:5)Open SQL获取数据行数限制
    Open SQL:3)多个表数据连接查询
    Open SQL:4)参照内表条件进行查询
    Open SQL:7)动态WHERE条件内表
    SAP应用界面开发:3)SELECTIONSCREEN 对象(1)
    SAP应用界面开发:3)Text Elements(文本元素)对象
  • 原文地址:https://www.cnblogs.com/zhuxiansheng/p/8079225.html
Copyright © 2011-2022 走看看