假设我想拥有一组对象,每个对象都应该有自己唯一的ID。不需要任何花哨的东西,只需要一个表示它是哪种类型的对象的字母,以及一个表示已经创建了多少对象的数字。例如,a0,a1,b0,c0,c1,c2,c3等。
我不想设置全局变量来跟踪每个对象已经存在多少,而是想用一个类来实现。像这样:
class uniqueIDGenerator
{
private $numberAObjs;
private $numberBObjs;
private $numberCObjs;
public function generateID ($type) {
if($type === "A") {
return 'a' . (int) $this->$numberAObjs++;
} else if($type === "B") {
return 'b' . (int) $this->$numberBObjs++;
} else if($type === "C") {
return 'c' . (int) $this->$numberCObjs++;
}
}
}
class obj
{
private $id;
function __construct($type) {
$this->id = uniqueIDGenerator::generateID($type);
}
}
这个问题是如果未实例化uniqueIDGenerator,它的generateID函数将始终为每个类型返回相同的值(例如a0,b0,c0等),因为它的私有变量实际上并未在内存中创建。同时,使它成为obj的属性将不起作用,因为每次创建obj时,它将拥有自己的uniqueIDGenerator实例,因此它也将始终返回a0,b0,c0,(假设它只被调用曾经在那个对象的方法中)等等。
唯一的选择似乎是使uniqueIDGenerator成为自己的全局实例,因此obj的构造函数可以引用它,但这似乎是糟糕的编码实践。是否有任何好的OOP方法可以将所有对象分开并组织起来?
答案 0 :(得分:1)
首先,您可以修改对象构造函数:
class obj
{
private $id;
function __construct($type, $id) {
$this->id = $id;
}
}
...
$id_generator = new uniqueIDGenerator(); // instanciation of the generator
$obj1 = new obj(type, $id_generator->generateID($type));
$obj2 = new obj(type, $id_generator->generateID($type));
$obj3 = new obj(type, $id_generator->generateID($type));
...
在我的项目中,我将创建一个名为ObjectFactory的类:
class ObjectFactory {
private $id_generator;
public function __construct($id_generator) {
$this->id_generator = $id_generator;
}
public function create_object($type) {
return new obj($this->id_generator->generateID($type));
}
}
...
$id_generator = new uniqueIDGenerator(); // instanciation of the generator
$obj_factory = new ObjectFactory($id_generator);
$obj1 = obj_factory->create_object($type);
$obj2 = obj_factory->create_object($type);
$obj3 = obj_factory->create_object($type);
最后,为了避免使用这个类的全局实例,你可以做一个Singleton(适应你的情况):
class uniqueIDGenerator
{
private $numberAObjs;
private $numberBObjs;
private $numberCObjs;
public static $instance = null;
public function __construct() {
$numberAObjs = 0;
$numberBObjs = 0;
$numberCObjs = 0;
}
public static function generateID($type) {
if(!self::$instance)
self::$instance = new uniqueIDGenerator();
return self::$instance->generateID2($type);
}
private function generateID2 ($type) {
if($type === "A") {
return 'a' . (int) $this->numberAObjs++;
} else if($type === "B") {
return 'b' . (int) $this->numberBObjs++;
} else if($type === "C") {
return 'c' . (int) $this->numberCObjs++;
}
}
}
uniqueIDGenerator::generateID("A");