PHP設計模式之適配器模式原理與用法分析

來源:http://news.mkq.online/ 作者:牛站新聞

本文實例講述了PHP設計模式之適配器模式原理與用法。分享給大家供大家參考,具體如下:

一、什麼是適配器模式

適配器模式有兩種:類適配器模式和對象適配器模式。其中類適配器模式使用繼承方式,而對象適配器模式使用組合方式。由於類適配器模式包含雙重繼承,而PHP並不支持雙重繼承,所以一般都採取結合繼承和實現的方式來模擬雙重繼承,即繼承一個類,同時實現一個接口。類適配器模式很簡單,但是與對象適配器模式相比,類適配器模式的靈活性稍弱。採用類適配器模式時,適配器繼承被適配者並實現一個接口;採用對象適配器模式時,適配器使用被適配者,並實現一個接口。

二、什麼時候使用適配器模式

適配器模式的作用就是解決兼容性問題,如果需要通過適配(使用多重繼承或組合)來結合兩個不兼容的系統,那就使用適配器模式。

三、類適配器模式

以貨幣兌換爲例:
01
<?php
02
/**
03

  • 類適配器模式
    04
  • 以貨幣兌換爲例
    05
    */
    06
    //美元計算類
    07
    class DollarCalc
    08
    {
    09
    private $dollar;
    10
    private $product;
    11
    private $service;
    12
    public $rate = 1;
    13
    public function requestCalc($product,$service)
    14
    {
    15
    $this->product = $product;
    16
    $this->service = $service;
    17
    $this->dollar = $this->product + $this->service;
    18
    return $this->requestTotal();
    19
    }
    20
    public function requestTotal()
    21
    {
    22
    $this->dollar
    = $this->rate;
    23
    return $this->dollar;
    24
    }
    25
    }
    26
    //歐元計算類
    27
    class EuroCalc
    28
    {
    29
    private $euro;
    30
    private $product;
    31
    private $service;
    32
    public $rate = 1;
    33
    public function requestCalc($product,$service)
    34
    {
    35
    $this->product = $product;
    36
    $this->service = $service;
    37
    $this->euro = $this->product + $this->service;
    38
    return $this->requestTotal();
    39
    }
    40
    public function requestTotal()
    41
    {
    42
    $this->euro *= $this->rate;
    43
    return $this->euro;
    44
    }
    45
    }
    46
    //歐元適配器接口
    47
    interface ITarget
    48
    {
    49
    function requester();
    50
    }
    51
    //歐元適配器實現
    52
    class EuroAdapter extends EuroCalc implements ITarget
    53
    {
    54
    public function construct()
    55
    {
    56
    $this->requester();
    57
    }
    58
    function requester()
    59
    {
    60
    $this->rate = .8111;
    61
    return $this->rate;
    62
    }
    63
    }
    64
    //客戶類
    65
    class Client
    66
    {
    67
    private $euroRequest;
    68
    private $dollarRequest;
    69
    public function
    construct()
    70
    {
    71
    $this->euroRequest = new EuroAdapter();
    72
    $this->dollarRequest = new DollarCalc();
    73
    $euro = "
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章