我正在尋找一些幫助,我寫了一個工廠模式,幾乎做我需要的,接受它會返回一個基於參數的新類。在php中使用工廠模式來構建汽車對象
我需要的是一種工廠模式,它接受一些東西並返回一個類型爲汽車的對象。該車將包含類型,型號,年份,製造和里程錶讀數等信息。
這是我AVE至今:
<?php
class Car_Factory_Pattern{
protected $_instance;
protected $_dependencies;
public function getInstance(){
if(null == self::$_instance){
self::$_instance == new self();
}
return self::$_instance;
}
public function create($class){
if(empty($class)){
throw new Exception('Cannot declare and empty class.');
}
if(!isset(self::$_dependencies)){
throw new Exception('The $dependencies are not set for this class');
}
if(!isset(self::$_dependencies[$class])){
throw new Exception('This class does not exist in the dependencies array');
}
if(isset(self::$_dependencies[$class]['params'])){
$new_class = new $class(implode(', ', self::$_dependencies[$class]['params']));
return $new_class;
}else{
$new_class = new $class();
return $new_class;
}
}
public function registerDependencies(array $array){
self::$_dependencies = $array;
}
}
你就需要爲這個數據結構爲:
函數依賴(){
$dependencies = array(
'Car_Class' => array(
'params' => array(
'Type',
'Model',
...
),
),
);
return $dependencies;
}
然後你通過這樣做來使課堂瞬間完成:
$factory = Car_Factory_Pattern()::getInstance();
$factory->registerDependencies(dependencies());
,然後讓我做的事:
$some_car = Car_Factory_Pattern()::create('Car_Class');
這樣做的問題是,我基本上是硬編碼的依賴關係,這適用於其他應用程序我工作,怎麼過 - 我需要這個什麼上課要做的是採取類型,模型,製作,年份和odom閱讀,並給我一個類型汽車的對象,無論你通過什麼,我可以創建一個類,它需要一系列的選項,我曾經希望如何工廠模式會爲我做到這一點 - 除非我錯了?
感謝您的幫助。
$new_class = new $class('Type,Model,Etc,Etc,will automaticly get more values depending on your array');
那是你真正想要的:
一個理智的使用工廠模式是爲了訪問單例對象,但是你的工廠總是做一個新的對象!那是你要的嗎? –