美文网首页
设计模式-中介者模式

设计模式-中介者模式

作者: 境里婆娑 | 来源:发表于2019-06-03 23:38 被阅读0次

    概念

    Define an object that encapsulates how a set of objects interact.Mediator promotes loose coupling by keeping objects from referring to each other explicitly,and it lets you vary their interaction independently.(用一个中介对象封装一系列的对象交互,中介者使各对象不需要显示地相互作用,从而使其耦合松散,而且可以独立地改变它们之间的交互。)

    中介者模式也叫做调停者模式,是什么意思呢?一个对象要和N多个对象交流,就像对
    象间的战争,很混乱。这时,需要加入一个中心,所有的类都和中心交流,中心说怎么理
    就怎么处理。

    可能这样听上去不是很理解,先举一个不使用中介者模式的例子。
    购物车类 ShoppingCart

    /**
     * 购物车
     * @author shuliangzhao
     * @Title: ShoppingCart
     * @ProjectName design-parent
     * @Description: TODO
     * @date 2019/6/3 21:06
     */
    public class ShoppingCart {
    
        private int number;
    
        public int getNumber() {
            return number;
        }
    
        public void setNumber(int number) {
            this.number = number;
        }
    
        //添加购物车
        public int addShoppingCart(){
            Inventory inventory = new Inventory();
            if (inventory.getComputerNumber() > number) {
                System.out.println("添加购物车"+number+"台");
                return number;
            }else {
                System.out.println("需要添加库存");
                return 1;
            }
        }
    
        public void clearShoppingCart() {
            System.out.println("清空购物车");
        }
    }
    

    订单Order

    /**
     * 订单
     * @author shuliangzhao
     * @Title: Order
     * @ProjectName design-parent
     * @Description: TODO
     * @date 2019/6/3 21:05
     */
    public class Order {
    
        //下单买电脑
        public void placeOrder(int number) {
            //库存
            ShoppingCart shoppingCart = new ShoppingCart();
            System.out.println("华为笔记本" + number + "台购买成功");
            shoppingCart.clearShoppingCart();
        }
    
    }
    

    库存Inventory

    /**
     * 库存
     * @author shuliangzhao
     * @Title: Inventory
     * @ProjectName design-parent
     * @Description: TODO
     * @date 2019/6/3 21:06
     */
    public class Inventory {
    
        private static int COMPUTER_NUMBER = 100;
    
        //库存增加
        public void add(int number) {
            COMPUTER_NUMBER += number;
            System.out.println("库存量为:" + COMPUTER_NUMBER);
        }
    
        //库存减少
        public void reduce(int number) {
            COMPUTER_NUMBER -= number;
    
            System.out.println("库存量为:" + COMPUTER_NUMBER);
        }
    
        //获取库存量
        public int getComputerNumber() {
            return COMPUTER_NUMBER;
        }
    }
    

    客户端

    /**
     * @author shuliangzhao
     * @Title: Client
     * @ProjectName design-parent
     * @Description: TODO
     * @date 2019/6/3 21:27
     */
    public class Client {
    
        public static void main(String[] args) {
    
            System.out.println("==========添加购物车=======");
            ShoppingCart shoppingCart = new ShoppingCart();
            shoppingCart.setNumber(3);
            shoppingCart.addShoppingCart();
            System.out.println("==========下订单==========");
            Order order = new Order();
            order.placeOrder(shoppingCart.getNumber());
            System.out.println("==========减库存==========");
            Inventory inventory = new Inventory();
            inventory.reduce(shoppingCart.getNumber());
        }
    }
    

    运行结果


    image.png

    运行结果也是我们期望的,三个类除了库存,另外两个类,都有关联。关联类越多,耦合性越大,要想修改一个就得修改一片,这不是面向对象设计所期望的。这只是简单的场景,如果更复杂的场景,我们看都看晕了,只能望而止步。
    大家都学过网络的基本知识,网络拓扑有三种类型:总线型、环型、星型。

    星型网络拓其实加入了一个中介者作为三个模块的交流核心,每个模块之间不再相互交流,要交流就通过中介者进行。每个模块只负责自己的业务逻辑,不属于自己的则丢给中介者来处理,简化了各模块之间的耦合关系
    我来改下上面代码

    建立了两个抽象类AbstractMediator和AbStractMediatorControl,每个对象只是与中介者Mediator之间产生依赖,与其他对象之间没有直接关系,AbstractMediator的作用是实现中介者的抽象定义,定义了一个抽象方法execute。
    AbstractMediator

    /**
     * 中介者
     * @author shuliangzhao
     * @Title: AbstractMediator
     * @ProjectName design-parent
     * @Description: TODO
     * @date 2019/6/3 21:53
     */
    public abstract class AbstractMediator {
    
        protected Order order;
        protected Inventory inventory;
        protected ShoppingCart shoppingCart;
    
        public AbstractMediator() {
            order = new Order(this);
            inventory = new Inventory(this);
            shoppingCart = new ShoppingCart(this);
        }
    
        public abstract Object execute(String str,Object... objects);
    
    }
    

    Mediator

    /**
     * @author shuliangzhao
     * @Title: Mediator
     * @ProjectName design-parent
     * @Description: TODO
     * @date 2019/6/3 22:02
     */
    public class Mediator extends AbstractMediator {
    
        @Override
        public Object execute(String str, Object... objects) {
            if (StringUtils.equals("order",str)) {
               return this.placeOrder((Integer) objects[0]);
            }else if (StringUtils.equals("cart",str)) {
               return this.addShoppingCart((Integer)objects[0]);
            }else if (StringUtils.equals("inv",str)) {
    
            }
            return null;
        }
    
    
        //下单买电脑
        private int placeOrder(int number) {
            //库存
            System.out.println("华为笔记本" + number + "台购买成功");
            super.shoppingCart.clearShoppingCart();
            return number;
        }
    
        //添加购物车
        private int addShoppingCart(int number){
            if (inventory.getComputerNumber() > number) {
                System.out.println("添加购物车"+number+"台");
                return number;
            }else {
                System.out.println("需要添加库存");
                return 1;
            }
        }
    
    
    }
    

    AbStractMediatorControl 实体继承这个类

    /**
     * 控制类
     * @author shuliangzhao
     * @Title: AbStractMediatorControl
     * @ProjectName design-parent
     * @Description: TODO
     * @date 2019/6/3 21:55
     */
    public abstract class AbStractMediatorControl {
    
        protected  AbstractMediator abstractMediator;
    
        public AbStractMediatorControl(AbstractMediator abstractMediator) {
            this.abstractMediator = abstractMediator;
        }
    }
    
    

    Inventory

    /**
     * @author shuliangzhao
     * @Title: Inventory
     * @ProjectName design-parent
     * @Description: TODO
     * @date 2019/6/3 21:58
     */
    public class Inventory extends AbStractMediatorControl {
        public Inventory(AbstractMediator abstractMediator) {
            super(abstractMediator);
        }
    
        private static int COMPUTER_NUMBER = 100;
    
        //库存增加
        public void add(int number) {
            COMPUTER_NUMBER += number;
            System.out.println("库存量为:" + COMPUTER_NUMBER);
        }
    
        //库存减少
        public void reduce(int number) {
    
            COMPUTER_NUMBER -= number;
            System.out.println("库存量为:" + COMPUTER_NUMBER);
        }
    
        //获取库存量
        public int getComputerNumber() {
            return COMPUTER_NUMBER;
        }
    }
    
    

    Order

    /**
     * @author shuliangzhao
     * @Title: Order
     * @ProjectName design-parent
     * @Description: TODO
     * @date 2019/6/3 21:57
     */
    public class Order extends AbStractMediatorControl {
        public Order(AbstractMediator abstractMediator) {
            super(abstractMediator);
        }
    
        public int placeOrder(int number) {
            return (int)super.abstractMediator.execute("order",number);
        }
    }
    
    

    ShoppingCart

    /**
     * @author shuliangzhao
     * @Title: ShoppingCart
     * @ProjectName design-parent
     * @Description: TODO
     * @date 2019/6/3 21:56
     */
    public class ShoppingCart extends AbStractMediatorControl {
    
        public ShoppingCart(AbstractMediator abstractMediator) {
            super(abstractMediator);
        }
    
        private int number;
    
        public int getNumber() {
            return number;
        }
    
        public void setNumber(int number) {
            this.number = number;
        }
    
        //添加购物车
        public int addShoppingCart(int number){
           return (int)super.abstractMediator.execute("cart",number);
        }
    
    
        public void clearShoppingCart() {
            System.out.println("清空购物车");
        }
    
    }
    
    

    客户端

    /**
     * @author shuliangzhao
     * @Title: Client
     * @ProjectName design-parent
     * @Description: TODO
     * @date 2019/6/3 22:35
     */
    public class Client {
    
        private static final int number = 2;
    
        public static void main(String[] args) {
            AbstractMediator abstractMediator = new Mediator();
            System.out.println("==========添加购物车=======");
            ShoppingCart shoppingCart = new ShoppingCart(abstractMediator);
            shoppingCart.addShoppingCart(number);
            System.out.println("==========下订单==========");
            Order order = new Order(abstractMediator);
            order.placeOrder(number);
            System.out.println("==========减库存==========");
            Inventory inventory = new Inventory(abstractMediator);
            inventory.reduce(number);
        }
    }
    
    

    运行结果


    image.png

    运行结果和上面是一样的,只是我们的代码数量增多了。不过逻辑更清晰了。

    中介者优点

    中介者模式的优点就是减少类间的依赖,把原有的一对多的依赖变成了一对一的依赖,
    同事类只依赖中介者,减少了依赖,当然同时也降低了类间的耦合。

    中介者缺点

    中介者模式的缺点就是中介者会膨胀得很大,而且逻辑复杂,原本N个对象直接的相互
    依赖关系转换为中介者和同事类的依赖关系,同事类越多,中介者的逻辑就越复杂。

    相关文章

      网友评论

          本文标题:设计模式-中介者模式

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