X.d 笔记

小Web,大世界

0%

设计模式(10):外观模式 Facdade

这是任何编程里面使用最多的一个模式了!只要有松耦合思想,就有外观模式!

外观模式 Facdade

为子系统中的一组接口提供一个一致的界面,外观模式定义了一个高层接口,这个接口使得这一子系统更加容易使用。。

问题:

A segment of the client community needs a simplified interface to the overall functionality of a complex subsystem.

意图:

  • Provide a unified interface to a set of interfaces in a subsystem. Facade defines a higher-level interface that makes the subsystem easier to use.
  • Wrap a complicated subsystem with a simpler interface

代码

例:这个模式用的太多了,也就是把复杂的业务流程给服务端处理,客户端只用自己已知的参数调用即可,比如去超市买一大堆东西,结帐时只需要把东西和钱往服务员一丢,一共多少钱,你的会员积分,促销品打折什么的都会自动给你算上。

代码1:服务端打包,对外只提供结帐方法

    package com.xdnote.DesignPattern.structural.facade;
    //外观模式,使用最最最最多的一种模式
    //对于功能的提供者来说,提供的功能为public,不提供的功能为private
    //在public的功能里面会用到private的功能就是外观模式.
    public class Seller {
        //模拟数据,出售的商品列表{id,price,factory},当然,用户只看的到前两项
        private final int[][] PRODUCTS = { {1,10,1},{2,15,1},{3,12,2},{4,8,2},{5,18,3} };
        private int[] getProduct(int id){
            for(int i=0,j=PRODUCTS.length;i<j;i++){
                int[] product =PRODUCTS[i];
                if(product[0]==id){
                    return product;
                }
            }
            return null;
        }
        
        private int sell(int product_price, int total){
            if(total >= product_price){
                System.out.println("销售成功");
            }
            return total - product_price;
        }
        
        private void made(int product_factory, int product_id){
            System.out.println("通知" + product_factory + "号库房生产商品" + product_id);
        }
        
        /**
         * 组合模式的方法,
         * 对用户购买的行为,组合
         * */
        public void buy(int id, int total){
            int[] product = getProduct(id);
            int product_price = product[1];
            int back = sell(product_price, total);
            if( back >= 0 ){
                int product_factory = product[2];
                made(product_factory, id);
                System.out.println("找零" + back);
            }else{
                System.out.println("money不够");
            }
        }
    }

代码二:客户端买单,传买的东西的ID,和付的钱

    public static void main(String[ ] args){
        Seller sell = new Seller();
        sell.buy(1, 30);
        sell.buy(1, 5);
        sell.buy(2, 15);
    }

小结

外观模式 Facdade

  • 使用频率:极高

一个Interface就是一个Facdade,不管是UI也好,Service好罢,可以说外观模式存在于任何代码中。

  • 利弊影响:极低

不论是面对向象还是面向过程的脚本语言,都可以用外观模式去抽象化交互