PHP:提供静态和非静态方法的类的设计模式
|
我的目标是创建可以静态和非静态方式使用的类.两种方式都必须使用相同的方法,但方式不同 非静态方式: $color = new Color("#fff");
$darkenColor = $color->darken(0.1);
静态方式: $darkenColor = Color::darken("#fff",0.1);
因此,在此示例中,darken既可以用于现有对象,也可以用作Color类的静态方法.但是根据它的使用方式,它使用不同的参数. 应该如何设计这样的课程?创建此类类的好模式是什么? 类将有许多不同的方法,因此它应该避免在每个方法的开头大量检查代码. PHP并不真正支持方法重载,因此实现起来并不是那么简单,但有一些方法.为什么提供静态和非静态? 我首先要问的是,如果确实需要提供静态和非静态方法.它似乎过于复杂,可能会使您的颜色类的用户感到困惑,并且似乎没有增加所有这些好处.我会采用非静态方法并完成它. 静态工厂类 你基本上想要的是静态工厂方法,所以你可以创建一个实现这个的额外类: class Color {
private $color;
public function __construct($color)
{
$this->color = $color;
}
public function darken($by)
{
// $this->color = [darkened color];
return $this;
}
}
class ColorFactory {
public static function darken($color,$by)
{
$color = new Color($color);
return $color->darken($by);
}
}
另一种方法是将静态方法放在Color中并给它一个不同的名称,例如createDarken(每次都应该是相同的,所以为方便用户,所有静态工厂方法都会被称为createX). callStatic 另一种可能性是使用魔术方法__call和__callStatic.代码看起来应该是这样的: class Color {
private $color;
public function __construct($color)
{
$this->color = $color;
}
// note the private modifier,and the changed function name.
// If we want to use __call and __callStatic,we can not have a function of the name we are calling in the class.
private function darkenPrivate($by)
{
// $this->color = [darkened color];
return $this;
}
public function __call($name,$arguments)
{
$functionName = $name . 'Private';
// TODO check if $functionName exists,otherwise we will get a loop
return call_user_func_array(
array($this,$functionName),$arguments
);
}
public static function __callStatic($name,$arguments)
{
$functionName = $name . 'Private';
$color = new Color($arguments[0]);
$arguments = array_shift($arguments);
// TODO check if $functionName exists,otherwise we will get a loop
call_user_func_array(
array($color,$arguments
);
return $color;
}
}
请注意,这有点凌乱.就个人而言,我不会使用这种方法,因为它对你的类的用户来说不是那么好(你甚至没有合适的PHPDocs).对于程序员来说,这是最简单的,因为在添加新函数时不需要添加大量额外代码. (编辑:安卓应用网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
