zoukankan      html  css  js  c++  java
  • PHP设计模式——策略模式

    <?php
    /**
     * 策略模式
     * 策略模式帮助构建的对象不必自身包含逻辑,而是能够根据需要利用其他对象中的算法
     * 
     * 在能够创建基于对象的,由自包含算法组成的可互换对象时,最佳的做法是使用策略模式 
     */
    interface Math{
        function calc($op1,$op2);
    }
    
    class Add implements Math{
        public function calc($op1,$op2) {
            return $op1 + $op2;
        }
    }
    
    class Sub implements Math{
        public function calc($op1,$op2) {
            return $op1 - $op2;
        }
    }
    
    //策略类
    class CMath{
        protected $_calc = NULL;
        public function __construct($type) {
            $this->_calc = new $type;
        }
        public function calc($op1,$op2) {
            return $this->_calc->calc($op1,$op2);
        }
    }
    
    //使用
    $type  = 'Add';
    $calc = new CMath($type);
    $result = $calc->calc(1, 100);
    echo '1 + 100 = '.$result.'<br>';
    
    //使用
    $type  = 'Sub';
    $calc = new CMath($type);
    $result = $calc->calc(1, 100);
    echo '1 - 100 = '.$result;
  • 相关阅读:
    mybatis逆向工程
    fastdfs搭建和使用
    solr学习笔记
    自己搭建anki服务器
    redis总结
    java基础——队列
    遍历文件夹下的文件,并且获取文件名字
    xls到xml
    xls文件导入数据库
    PyCharm怎样添加Qt designer
  • 原文地址:https://www.cnblogs.com/tlxma/p/5210704.html
Copyright © 2011-2022 走看看