• facade模式


    <?php
    /**
     * facade模式
     * 将杂乱的代码封装为干净的接口
     * 
     * 来自<<深入PHP面向对象,模式与实践>>
     */
    
    
    /**
     * 
     * 我们来看一下不使用facade模式比较极端的一个例子
     * 以下代码只是为了从log中获取信息,并将其转为对象数据
     */
    function getProductFileLines($file) {
        return file($file);
    }
    
    function getProductObjectFromId($id, $productName) {
        return new Product($id, $productName);
    }
    
    function getNameFromLine($line) {
        if (preg_match("/.*-(.*)sd+/", $line, $arr)) {
            return str_replace('_', ' ', $array[1]);
        }
        return '';
    }
    
    function getIdFromLine($line) {
        if (preg_match("/^(d{1,3})-/", $line, $arr)) {
            return $arr[1];
        }
        return -1;
    }
    
    class Product {
        public $id;
        public $name;
        
        public function __construct($id, $name) {
            $this->id = $id;
            $this->name = $name;
        }
    }
    
    /**
     * 为杂乱的代码生成干净的接口
     * 使用facade模式将上面的代码封装为干净的接口
     */
    class ProductFacade {
        private $products = array();
        
        public 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);
            }
        }
        
        public function getProducts() {
            return $this->products;
        }
        
        public function getProduct($id) {
            return $this->products[$id];
        }
    }
    
    $facade = new ProductFacade('test.txt');
    $product = $facade->getProduct(1234);
  • 相关阅读:
    从xib初始化的UIView如何继承?
    no implicit conversion of nil into String
    @synchronized(self) 加锁引起的Crash
    iOS手工Crash解析
    iOS线程While-True死循环会发生什么
    2019年新年总结
    218. The Skyline Problem-Hard
    ReplayKit 启动录制按钮 RPSystemBroadcastPickerView 的使用
    S212-搜索+字典树-212. Word Search II-(Hard)
    mybatis批量生成
  • 原文地址:https://www.cnblogs.com/mtima/p/3176519.html
Copyright © 2020-2023  润新知