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

    策略模式:

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

    <?php
    namespace FrameWork;
    /**
     * 策略模式
     * 根据不同性别展示不同内容
     * 一下代码 示意 一个商城系统 根据用户不同性别 展示不同的广告和分类
     */
    
    interface UserStrategy
    {
        //展示广告
        public function showAd();
    
        //展示分类
        public function showCategory();
    }
    
    //男性策略类
    class MaleStrategy implements UserStrategy
    {
        public function showAd()
        {
            echo '男士广告iphone 6s';
        }
    
        public function showCategory()
        {
            echo '男士显示电子产品';
        }
    }
    
    //女性策略类
    class FemaleStrategy implements UserStrategy
    {
        public function showAd()
        {
            echo '女士广告 Dior香水';
        }
    
        public function showCategory()
        {
            echo '女士 女装';
        }
    }
    
    //页面展示类
    class Page
    {
        protected $strategy;
        //展示页面
        public function Index()
        {
            $this->strategy->showAd();
            $this->strategy->showCategory();
        }
    
        //设置策略
        public function setStrategy(UserStrategy $strategy)
        {
            $this->strategy = $strategy;
        }
    }
    
    if(isset($_REQUEST['sex'])){
        //设置了 性别
        $strategy = new MaleStrategy();
        $page = new Page();
        $page->setStrategy($strategy);
        $page->Index();
    }
  • 相关阅读:
    NSIS 资料
    git 强制刷新,放弃更改
    Using 1.7 requires compiling with Android 4.4 (KitKat); currently using API 8
    …gen already exists but is not a source folder. Convert to a source folder or rename it [closed]
    eclipse
    Timeout in android httpclient
    git command
    L1-032. Left-pad
    L1-030. 一帮一
    L1-028. 判断素数
  • 原文地址:https://www.cnblogs.com/onephp/p/6107012.html
Copyright © 2011-2022 走看看