码迷,mamicode.com
首页 > Web开发 > 详细

大话设计模式第二章---商场促销简单工厂模式、策略模式 PHP实现及对比

时间:2015-08-29 09:42:26      阅读:179      评论:0      收藏:0      [点我收藏+]

标签:

简单工厂模式:

<?php
abstract class Cash_super {
    abstract public function accept_cash(float $money);
}

class Cash_normal extends Cash_super {
    public function accept_cash(float $money) {
        return $money;
    }
}

class Cash_rebate extends Cash_super {
    private $_money_rebate;
    public function __construct(float $money_rebate) {
        $this->_money_rebate = $money_rebate;
    }

    public function accept_cash(float $money) {
        return $money * $this->_money_rebate;
    }
}

class Cash_return extends Cash_super {
    private $_money_condition = 0;
    private $_money_return = 0;

    public function __construct(float $money_condition, float $money_return) {
        $this->_money_condition = $money_condition;
        $this->_money_return = $money_return;
    }
    public function accept_cash(float $money) {
        $result = $money;
        if ($money >= $this->_money_condition) {
            return $money - floor($money/$this->_money_condition) * $this->_money_return;
        }
        return $result;
    }
}

class Cash_factory {
    public static function create_cash_accept($type) : Cash_super {
        $cs = null;
        switch ($type) {
        case ‘normal‘:
            $cs = new Cash_normal();
            break;
        case ‘300-100‘:
            $cs = new Cash_return(300, 100);
            break;
        case ‘0.8‘:
            $cs = new Cash_rebate(0.8);
            break;
        }
        return $cs;
    }
}

$csuper = Cash_factory::create_cash_accept(‘300-100‘);
$total_price = $csuper->accept_cash(30000);
echo $total_price;

策略与简单工厂模式的组合:

class Cash_context {
    private $cs = null;

    public function __construct($type) {
        switch ($type) {
        case ‘normal‘:
            $this->cs = new Cash_normal();
            break;
        case ‘300-100‘:
            $this->cs = new Cash_return(300,100);
            break;
        case ‘0.8‘:
            $this->cs = new Cash_rebate(0.8);
            break;
        }
    }

    public function get_result($money) {
        return $this->cs->accept_cash($money);
    }
}

$cc = new Cash_context(‘300-100‘);
$total_price = 0;
$total_price = $cc->get_result(5000);
echo $total_price;

说明:

  简单工厂模式需要让客户端认识两个类。Cash_super和Cash_factory。

  策略与简单工厂结合,客户端只需要认识一个类 Cash_context,降低了耦合。

  策略模式是一种定义一系列算法的方法,从概念上来看,所有这些算法完成的都是相同的工作,只是实现不同,它可以以相同的方式调用所有的算法,减少了各种算法类与使用算法之间的耦合;

大话设计模式第二章---商场促销简单工厂模式、策略模式 PHP实现及对比

标签:

原文地址:http://www.cnblogs.com/wy0314/p/4768387.html

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