【发布时间】:2011-08-23 09:47:21
【问题描述】:
实现这种行为的最佳模式是什么?
我有很多方法,比如 method_1 .. method_N,它们都可以通过一个参数进行参数化,比如 $k。我想把它们作为静态方法放在一个类中,所以我当然可以这样写我的 ComputationClass:
class Computation {
static function method1( $k, $otherParams ) { ... }
static function method2( $k, $otherParams ) { ... }
static function method3( $k, $otherParams ) { ... }
}
现在,由于 $k 属于特定范围的值,例如 {'dog', 'cat', 'mouse'},我想创建许多 Computation 子类,每个子类对应每个可能的值。
class Computation_Dog extends Computation {
static function method1( $otherParams ) { parent::method1('dog', $otherParams); }
static function method2( $otherParams ) { parent::method2('dog', $otherParams); }
static function method3( $otherParams ) { parent::method3('dog', $otherParams); }
}
class Computation_Cat extends Computation { .. }
class Computation_Mouse extends Computation { .. }
但这很丑陋,让我放弃了继承的优势:如果我向 Computation 添加一个方法会发生什么?必须编辑所有子类.. 然后我巧妙地切换到这个:
abstract class Computation {
abstract static function getK();
static function method1($otherParams) { ... self::getK() .. }
static function method2($otherParams) { ... self::getK() .. }
static function method3($otherParams) { ... self::getK() .. }
}
class Computation_Dog extends Computation {
static function getK() { return 'dog'; }
}
不错的尝试,但它不起作用,因为静态方法似乎不记得继承堆栈,并且 self::getK() 会调用 Computation::getK() 而不是 Computation_Dog::getK()。
嗯..希望足够清楚..您将如何设计这种行为? PS:我真的需要它们作为静态方法
谢谢
【问题讨论】:
标签: php inheritance static design-patterns