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

    这种模式类似于工厂模式。但又不相同。 下面以 实际场景举例

    咱们中国人,有会说英语的,有会说汉语的。那么咱们就以实际的代码来演示

    [PHP] 纯文本查看 复制代码
    01
    02
    03
    04
    05
    06
    07
    08
    09
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    <?php
    /**
     * 中国人的接口
     */
    interface IChinese
    {
        public function speek();//都会说话
    }
    /**
     * 英语翻译,也是中国人
     *
     */
    class EChinese implements IChinese
    {
        public function speek()
        {
            return 'speek english';//说英文
        }
         
    }
    /**
     * 普通中国人
     */
    class NChinese implements IChinese
    {
        public function speek()
        {
            return 'speek chinese';//普通中国人说汉语
        }
    }
    /**
     * 中国人的实际类
     */
    class Chinese implements IChinese
    {
        public $obj;//当前角色
        public function setManRole($role)//设置角色
        {
            $this->obj = $role;
        }
        public function speek()//说话
        {
           return  $this->obj->speek();//调用对应的人
        }
    }
    //实际代码
    $man = new Chinese();//实例化
    $man->setManRole(new EChinese());//切换翻译角色
    echo $man->speek() .'<hr>';//说话
    $man->setManRole(new NChinese());//切换到普通人
    echo $man->speek();//再说话
    ?>
    speek english
    speek chinese
  • 相关阅读:
    How to debug with IntelliJ IDEA + Grails 2.3.x (转)
    Lucene教程具体解释
    html中滚动栏的样式
    centos下ant的安装
    qt的资源替换搜索QDir具体解释
    strtok和strtok_r
    文件读写、游标
    Rational Rose 2007 &amp;Rational Rose 2003 下载及破解方法和汉化文件下载
    算法6-5:哈希表应用之集合
    javaEE jdbc编程步骤
  • 原文地址:https://www.cnblogs.com/ghjbk/p/6670236.html
Copyright © 2011-2022 走看看