【问题标题】:Should data that is the same across all class instantiations be held in a separate, static class?是否应该将所有类实例中相同的数据保存在单独的静态类中?
【发布时间】:2011-11-29 13:12:29
【问题描述】:

如果我有一个将被实例化的类,它需要引用每个类都相同的数据和/或函数。应该如何处理以遵循正确的编程实践

示例(在 PHP 中):

class Column {
    $_type = null;
    $_validTypes = /* Large array of type choices */;

    public function __construct( $type ) {
        if( type_is_valid( $type ) ) {
             $_type = $type;
        }
    }

    public function type_is_valid( $type ) {
        return in_array( $type, $_validTypes );
    }
}

然后每次创建一个 Column 时,它都会保存 $_validTypes 变量。这个变量只需要在内存中定义一次,所有创建的列都可以引用静态函数type_is_valid,该静态类将保存$_validTypes变量,只声明一次。

静态类的想法,比如ColumnHelperColumnHandler 是处理这个问题的好方法吗?或者有没有办法在这个类中保存静态数据和方法?还是为每个列重新定义$_validTypes 是一种不错的做事方式?

【问题讨论】:

    标签: php static static-methods static-classes


    【解决方案1】:

    一个选项是为列配置创建一个新模型,例如

    class ColumnConfig {
        private $validTypes;
        public isValid($type){
            return isset($this->validType($type))?true:false;
        }
    }
    

    然后将其添加到 API(如果有的话),或者创建一个全局实例,例如

    $cc = new ColumnConfig();
    class Column {
        private $cc;
        function __construct($type){
            $this->cc = $this->api->getCC(); // if you have api
            global $cc; // assuming you have no api, an you create a global $cc instance once.
            $this->cc = $cc; // <-- this would pass only reference to $cc not a copy of $cc itself.
    
            if ($this->cc->isValid($type)){
              ....
            }
        }
    }
    

    听起来不错。

    【讨论】:

      猜你喜欢
      • 2015-05-31
      • 1970-01-01
      • 1970-01-01
      • 2013-10-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-19
      • 1970-01-01
      相关资源
      最近更新 更多