zoukankan      html  css  js  c++  java
  • 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);
  • 相关阅读:
    Linux常用命令(文件常用命令)
    Spring中的核心思想
    AOP中重要概念
    Spring框架中2种生成代理对象的方法
    python模块详解 | psutil
    Linux学习笔记 | 常见错误之无法获得锁
    python学习笔记 | 列表去重
    CentOS | python3.7安装指南
    selenium爬虫 | 爬取疫情实时动态(二)
    selenium爬虫 | 爬取疫情实时动态
  • 原文地址:https://www.cnblogs.com/mtima/p/3176519.html
Copyright © 2011-2022 走看看