Blogger Information
Blog 6
fans 3
comment 1
visits 8885
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
设计模式之策略模式
齐天大圣的博客
Original
1270 people have browsed it

策略模式:将一组特定的行为和算法封装成类,以适应某种特定的上下文环境,这种模式就是策略模式。

场景:商品的促销活动类型有很多,如:买满减活动、打折、送积分,如何来完成该需求。

<?php

Interface Strategy
{
    function sale ();
}

// 打折策略
class DiscountStrategy implements Strategy
{
    private $money = 0;    // 总价
    private $rate = 100;    // 折扣

    public function __construct($money, $rate)
    {
        $this->money = $money;
        $this->rate = $rate;
    }

    public function sale ()
    {
        $money = $this->money - round($this->money * ($this->rate / 100), 2);
        echo "总价{$this->money},打完折后价格:$money\n";
    }
}

// 送积分
class ScoreStrategy implements Strategy
{
    private $money = 0;    // 总价
    private $rate = 0;    // 兑换比率

    public function __construct($money, $rate)
    {
        $this->money = $money;
        $this->rate = $rate;
    }

    public function sale ()
    {
        $score = $this->money * ($this->rate / 100);
        echo "送积分$score\n";
    }
}

class Page
{
    public function buy ()
    {
        $obj = $_GET['obj'];
        echo (new $obj(100,10))->sale();
    }
}

(new Page())->buy();




Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post