首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >PHP设计模式

PHP设计模式
EN

Stack Overflow用户
提问于 2013-02-28 05:20:55
回答 3查看 245关注 0票数 1

我有一个重复出现的问题,我目前正在处理这样的问题-

一个POST变量进入脚本,它有一个平台,平台来自一个列表,例如: xbox,ps3,pc,mobileapp,mobilegame等

对于每个不同的平台,我希望能够在我的脚本中做一些不同的事情,但在某些情况下,我希望代码在此刻做一些类似的事情,我这样做:

代码语言:javascript
运行
复制
$platformArray = array(
   'ps3'=>array('displayName'=>'playstation 3','function'=>'funcPS3'),
   'xbox'=>array('displayName'=>'Xbox','function'=>'funcXbox')
)
//similar amongst all platforms code on line below
echo 'you have a :'.$platformArray[$_POST['platform']]['displayName'].' for playing       games';

call_user_func($platformArray[$_POST['platform']['function']);

function funcPS3(){
   echo 'ps3 specific code'; 
}

 function funcXbox(){
   echo 'xbox specific code';
 }

我想在我的代码中转向OOP方法,我想使用对象作为我的数据存储媒介,而不是像我现在所做的那样使用数组,但我有时确实需要提前在代码中定义属性,如果不使用对象,我该如何做以上的事情呢?

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2013-02-28 05:35:03

我将从一个非常简单的OO版本,到被认为是“好的”OO代码,使用多态行为和避免全局状态。

1.不是多态的,有全局静态数据

这非常糟糕,因为它实际上只是过程代码上的一个包装器对象。它需要一个函数映射来调用每种类型的平台。

代码语言:javascript
运行
复制
class Platform {    
    private static $platformArray = array(
       'ps3' => array(
           'displayName'=>'playstation 3',
           'function'=>'funcPS3'
        ),
       'xbox' => array(
           'displayName'=>'Xbox',
           'function'=>'funcXbox'
       )
    );

    private $type;

    public function __construct($type) {
        if (!array_key_exists($type, self::$platformArray)) {
             throw new Exception("Invalid Platform type $type" );
        }
        $this->type = $type;
    } 

    public function printCode() {
        // This was a question embedded within your question, you can use 
        // http://php.net/manual/en/function.call-user-func.php
        // and pass an instance with a method name.     
        return call_user_func( array($this, self::$platformArray[$this->type]) );
    }

    private function funcPS3(){
        echo 'ps3 specific code'; 
    }

    private function funcXbox(){
        echo 'xbox specific code';
    }    
}

$plat = new Platform($_POST['platform']);
$plat->printCode();

2.多态...但它仍然使用全局数据

By creating a base class您可以在子类中实现行为,为每个关注点创建单独的类。这里最大的问题是子类需要向全局注册表注册。

代码语言:javascript
运行
复制
abstract class Platform {
    abstract protected function getCode();
    public function printCode() {
        echo $this->getCode();
    }

    private function __construct() {} // so only factory can instantiate it
    private static $platformArray = array();

    public static function create($type) {
        if (!array_key_exists($type, self::$platformArray)) {
             throw new Exception("Invalid Platform type $type" );
        }
        return new self::$platformArray[$type];

    }         

    public static function addPlatform($type, $ctor) {
        if (!is_subclass_of($ctor, 'Platform')) {
             throw new Exception("Invalid Constructor for Platform $ctor" );   
        }
        self::$platformArray[$type] = $ctor;
    }
}

class PlatformXBox extends Platform{
     protected function getCode() {
         return 'xbox specific code';
     }
}
Platform::addPlatform('xbox', 'PlatformXBox');

class PlatformPs3 extends Platform {
     protected function getCode() {
         return 'ps3 specific code';
     }
}
Platform::addPlatform('ps3', 'PlatformPs3');

$plat = Platform::create($_POST['platform']);
$plat->printCode();

3.多态,无全局数据

By putting your code into a namespace,避免了基类中的静态代码,也避免了将post参数直接映射到类中的危险。

代码语言:javascript
运行
复制
namespace platform {

interface IPlatform {
   public function getDisplayName();
   public function getCode();
}

class PlatformFactory {
    static public function create($platformType) {           
        $className = "\\platform\\$platformType";
        if ( !is_subclass_of($className, "\\platform\\IPlatform") ){
            return null;
        }
        return new $className;
    }
}

class Xbox implements IPlatform {
    public function getDisplayName(){
        return 'xbox';
    }
    public function getCode(){
       return 'xbox code';   
    }
}

class Ps3 implements IPlatform {
    public function getDisplayName(){
        return 'ps3';
    }
    public function getCode(){
        return 'ps3 code';   
    }
}

}

现在,您可以像下面这样使用这些类

代码语言:javascript
运行
复制
$platform = platform\PlatformFactory::create('xbox');
echo $platform->getCode() ."\n" ;

$platform2 = platform\PlatformFactory::create('ps3');
echo $platform2->getDisplayName()."\n";

$noPlatform = platform\PlatformFactory::create('dontexist');
if ($noPlatform) {
    echo "This is bad, plaftorm 'dontexist' shouldn't have been created";
} else {
    echo "Platform 'dontexist' doesn't exist";
}
票数 0
EN

Stack Overflow用户

发布于 2013-02-28 18:56:50

我建议您从了解多态性开始。This lecture应该是一个好的开始。

当您尝试创建基于某个标志的行为时,您应该实现两个具有相同接口的类:

代码语言:javascript
运行
复制
class Xbox
{
    private $displayName = 'XBox 360';

    public function identify()
    {
        // Xbox-specific stuff
        return  ':::::::::::'. $this->displayName;
    }
}

class PS3
{

    private $displayName = 'Playstation 3';

    public function identify()
    {
        // playstation-specific stuff
        return '+++'. $this->displayName . '+++';
    }
}

这两个类有同名的方法,但做不同的事情;

代码语言:javascript
运行
复制
$platform = $_POST['platform'];
// classes in PHP are case-insensitive
// expected values would be:  xbox, Xbox, ps3, pS3
if ( !class_exists($platform) )
{
     echo "Platform '{$platform}' is not supported";
     exit; 
     // since continuing at this point would cause a fatal error, 
     // better to simply exit
}

$object = new $platform;
echo $object->identify();

基本上,在这种情况下,您并不关心您使用的是哪种类型的平台。你所需要知道的就是它们都有相同的公共接口。这被称为“多态行为”。

票数 4
EN

Stack Overflow用户

发布于 2013-02-28 05:40:04

您可能希望创建一个名为platforms的类,并在该类中为每个平台创建一个不同的方法:

代码语言:javascript
运行
复制
class platforms {
   //Create your variables here, also called properties.
   public $displayName;

   //Create a function, also called a method for each platform you intent to use.
   public function xboxPlatform(){
        //Code comes here what you want to do.
   }
}

希望这能有所帮助。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/15122651

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档