我刚刚阅读了Factory Method。我知道它提供了一种将实例化委托给子类的方法。但我不能理解它在真实场景中的可能用途。
谁能举一个典型的例子来说明如何使用工厂方法模式,以便我能与我所读到的内容联系起来。
对于哪种工厂方法模式是最好的解决方案,一个问题陈述就足以说明这一点。
发布于 2010-03-05 18:54:06
实现工厂设计模式的类充当多个类之间的桥梁。考虑使用多个数据库服务器(如SQL Server和Oracle )的示例。如果您正在使用SQL Server数据库作为后端开发应用程序,但将来需要将后端数据库更改为oracle,那么如果您没有按照工厂设计模式编写代码,则需要修改所有代码。
在工厂设计模式中,你只需要做很少的工作就可以做到这一点。一个实现工厂设计模式的类会照顾你,减轻你的负担。从数据库服务器切换一点也不会困扰你。您只需在配置文件中进行一些小的更改。
发布于 2015-01-01 05:33:32
一个静态创建的php代码示例:
interface DbTable
{
public function doSomething(): void;
}
class MySqlTable implements DbTable
{
public function doSomething(): void
{ }
}
class OracleTable implements DbTable
{
public function doSomething(): void
{ }
}
class TableFactory
{
public static function createTable(string $type = null): DbTable
{
if ($type === 'oracle') {
return new OracleTable();
}
return new MySqlTable(); // default is mysql
}
}
// client
$oracleTable = TableFactory::createTable('oracle');
$oracleTable->doSomething();要使其更动态(稍后修改较少),请执行以下操作:
interface DbTable
{
public function doSomething(): void;
}
class MySqlTable implements DbTable
{
public function doSomething(): void
{ }
}
class OracleTable implements DbTable
{
public function doSomething(): void
{ }
}
class TableFactory
{
public static function createTable(string $tableName = null): DbTable
{
$className = __NAMESPACE__ . $tableName . 'Table';
if (class_exists($className)) {
$table = new $className();
if ($table instanceof DbTable) {
return $table;
}
}
throw new \Exception("Class $className doesn't exists or it's not implementing DbTable interface");
}
}
$tbl = TableFactory::createTable('Oracle');
$tbl->doSomething();发布于 2010-03-05 18:54:58
来自我现在正在开发的API:
WebGalleryFactory factory = WebGalleryFactory.newInstance (WebGalleryType.PICASA);
WebAlbum album = factory.createAlbum (title, description);在这个例子中,我使用Factory方法来创建某种类型的Abstract Factory (在这个例子中是PICASA)。
这两种模式通常一起使用。
https://stackoverflow.com/questions/2386125
复制相似问题