码迷,mamicode.com
首页 > 其他好文 > 详细

适配器模式例子

时间:2016-01-21 00:07:49      阅读:154      评论:0      收藏:0      [点我收藏+]

标签:

<?php

class Message{
  private $message;
  function __construct($m){
    $ip = $_SERVER(‘REMDTE_ADDR‘);
    $this->message = $ip.‘:‘.$m;
  }
  function getMessage(){
    return $this->message;
  }
}

//适配器类,不改变原有类的情况下.增加新的借口
class MessageAdapter extends Message{
  private $ip;
  private $text;
  function __construct(){
    //适配器往往需要调用父类的某些方法
    parent::__construct($m){
      $message = $this->getMessage();
      $arr = explode(":", $message);
      $this->ip = $arr[0];
      $this->text = $arr[1];
    }
  }
  function getip(){
    return $this->ip;
  }
  function getText(){
    return $this->text;
  }
}

class LogFile{
  public static function write($messageObj){
    $message->$messageObj->getMessage();
    $h = fopen(‘./log.log‘, ‘a‘);
    fwrite($h, $message."\n");
    fclose($h);
  }
}

class LogCSV{
  public static function write($messageObj){
    $ip = $messageObj->getIp();
    $text = $messageObj->getText();
    $message = $ip.‘,‘.$text;
    $h = fopen(‘./log.csv‘, ‘a‘);
    fwrite($h, $message."\n");
    fclose($h);
  }
}

$m = new MessageAdapter(‘this is a log!!‘);
LogFile::write($m);


适配器模式例子

标签:

原文地址:http://www.cnblogs.com/meibao/p/5146865.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!