zoukankan      html  css  js  c++  java
  • B4:策略模式 Strategy

    它定义了算法家族,分别封装起来,让他们之间可互相替换,此模式让算法的变化,不会影响到使用算法的客户.

    UML

    示例代码:

    abstract class Strategy
    {
        protected $money;
    
        public function __construct($money)
        {
            $this->money = $money;
        }
    
        abstract public function calcMoney();
    
        public function getMoney()
        {
            return $this->money;
        }
    }
    
    // 正常
    class MoneyNomarl extends Strategy
    {
        public function calcMoney()
        {
            return $this->money;
        }
    }
    
    // 返利
    class MoneyRebate extends Strategy
    {
        public function calcMoney()
        {
            return $this->money + $this->getRebate();
        }
    
        protected function getRebate()
        {
            return (int) $this->money * 0.1;
        }
    }
    
    class StrategyContext
    {
        private $strategy;
    
        public function set(Strategy $strategy)
        {
            $this->strategy = $strategy;
        }
    
        public function getMoney()
        {
            return $this->strategy->calcMoney();
        }
    }
    
    $money = 100;
    $strategy = new StrategyContext();
    $strategy->set(new MoneyNomarl($money));
    echo $strategy->getMoney();
    

      

  • 相关阅读:
    简单的逻辑学 笔记
    中国古代文化常识 笔记
    Docker 使用官方镜像
    Docker 入门 之基本命令
    Windows.form增删改查
    自定义控件
    LISTVIEW
    窗体布局
    计算器
    登录
  • 原文地址:https://www.cnblogs.com/itfenqing/p/7788787.html
Copyright © 2011-2022 走看看