zoukankan      html  css  js  c++  java
  • 让面向对象编程更加灵活的的模式-----外观模式

    问题

    当使用子系统的代码是,有时候发现自己过于深入的调用子系统的逻辑代码,如果子系统代码总是不断变化,而你的代码缺又在许多不同地方与子系统代码交互,那么随着子系统的发展,代码越来越维护困难,外观模式要解决的就是使系统中的各层互相独立,以便项目中某一部分的修改尽量不影响其他地方。

    代码实现

    <?php
    /*
    appearance.php
    外观模式
    */
    
    function getProductFileLines($file){
        return file($file);
    }
    
    function getProductObjectFromId($id,$productname){
        //查询数据库
        return new product($id,$productname);
    }
    
    function getNameFromLine($line){
        if(preg_match("/.*-(.*)sd+/",$line,$array)){
            return str_replace('_',' ',$array[1]);
        }
        return '';
    }
    
    function getIdFromLine($line){
        if(preg_match("/^(d{1,3})-/",$line,$array)){
            return $array[1];
        }
        return -1;
    }
    
    class Product{
        public $id;
        public $name;
        function __construct($id,$name){
            $this->id = $id;
            $this->name = $name;
        }
    }
    
    
    
    
    //client,直接调用,那么我们的代码和子系统紧密的耦合在一起
    $lines = getProductFileLines('test.txt');
    $obj = array();
    foreach ($lines as $line) {
        $id = getIdFromLine($line);
    
        $name = getNameFromLine($line);
        $obj[$id] = getProductObjectFromId($id,$name);
    }
    
    //采用外观模式
    class ProductFacade{
        private $products = array();
        function __construct($file){
            $this->file = $file;
            $this->compile();
        }
        private function compile(){
            $lines = getProductFileLines($this->file);
            foreach ($lines as $line) {
                $id = getIdFromLine($line);
                $name = getNameFromLine($line);
                $this->products[$id] = getProductObjectFromId($id,$name);
            }
        }
    
        function getProducts(){
            return $this->products;
        }
    
        function getProduct($id){
            return $this->products[$id];
        }
    }
    
    //client,
    $ProductFacade = new ProductFacade('test.txt');
    print_r($ProductFacade->getProducts());
    ?>

    效果

    分离了项目中的不同部分

    使得客户端访问代码变得更简洁,方便

    只在一个地方调用子系统(productfacade中),减少了出错的可能性,并可预估子系统修改带来的问题所在

  • 相关阅读:
    Hbase­优化方案
    ssh 登录
    微软2017校招笔试题3 registration day
    微软2017校招笔试题2 composition
    STL中的查找算法
    leetcode-188 买卖股票4
    leetcode-306 Additive Number
    网络安全(3): 数据完整性校验
    网络安全(2)-数据加解密
    linux共享库
  • 原文地址:https://www.cnblogs.com/rcjtom/p/6066221.html
Copyright © 2011-2022 走看看