zoukankan      html  css  js  c++  java
  • 设计模式 适配器模式

    适配器模式

    就是不修改原有类的基础上 加一个中间转换层,以使其符合新需求

    说白了,就是对原有类的扩展,怎么扩展,继承呗

    例如下:

     1 <?php
     2 
     3 //最原始的错误处理
     4 class Error {
     5     public $_error;
     6 
     7     public function __construct($error) {
     8         $this->_error = $error;
     9     }
    10 
    11     public function getError() {
    12         return $this->_error;
    13     }
    14 }
    15 
    16 class Log {
    17     public $errObj;
    18 
    19     public function __construct(Error $obj) {
    20         $this->errObj = $obj;
    21     }
    22 
    23     public function writeLog() {
    24          fwrite(STDERR, $this->errObj->getError());
    25     }
    26 }
    27 
    28 $err = new Error('1:wrong!');
    29 
    30 $log = new Log($err);
    31 $log->writeLog();
    32 
    33 //需求变了,本着那啥和啥的原则,类是不能轻易改动的....
    34 class LogCsv{
    35     public $csvFile = 'log.txt';
    36 
    37     public $errObj;
    38 
    39     public function __construct(Error $obj)
    40     {
    41         $this->errObj = $obj;
    42     }
    43 
    44     public function writeLog()
    45     {
    46         $line = '';
    47         $line .= $this->errObj->getNum();
    48         $line .=' ';
    49         $line .= $this->errObj->getText();
    50 
    51         file_put_contents($this->csvFile, $line);
    52     }
    53 }
    54 
    55 //错误处理适配器
    56 class ErrorAdapter extends Error{
    57     public $num;
    58     public $text;
    59 
    60     public function __construct($error)
    61     {
    62         $arr = explode(':', $error);
    63         $this->num = $arr[0];
    64         $this->text = $arr[1];
    65     }
    66 
    67     public function getNum()
    68     {
    69         return $this->num;
    70     }
    71     public function getText()
    72     {
    73         return $this->text;
    74     }
    75 }
    76 $err = new ErrorAdapter('1:wrong!');
    77 
    78 $log = new LogCsv($err);
    79 $log->writeLog();
  • 相关阅读:
    AutoCAD开发8---获取块属性(C#)
    AutoCAD开发7--坐标转换
    AutoCAD开发6--修改高程
    遍历ArcMap已加载数据的属性
    shapefile添加字段 设置文件名为字段内容
    skyline开发——加载Shapefile文件
    skyline开发——读取Shapefile要素属性
    python 中文乱码解决
    python实现模拟登录【转】
    列表页url参数格式分析【求指教】
  • 原文地址:https://www.cnblogs.com/zper/p/4140152.html
Copyright © 2011-2022 走看看