2014-10-09 31 views

回答

1

工廠用於根據上下文創建單個服務。抽象工廠用於根據上下文創建許多類似的服務。 例如,假設您的應用程序需要單個存儲庫「UsersRepository」,它連接到您的數據庫並允許您從「Users」表中獲取數據。你會爲此服務創建一個工廠如下:

class UsersRepositoryFactory implements FactoryInterface 
{ 
    public createService(ServiceLocatorInterface $serviceLocator) 
    { 
     return new \MyApp\Repository\UsersRepository(); 
    } 
} 

然而,在現實世界中,你可能想在你的應用中有許多表進行交互,因此,你應該考慮使用抽象工廠創建每個倉庫服務表。

class RepositoryAbstractFactory implements AbstractFactoryInterface 
{ 
    canCreateServiceWithName(ServiceLocatorInterface $serviceLocator, $name, $requestedName) 
    { 
     return class_exists('\MyApp\Repository\'.$requestedName); 
    } 

    createServiceWithName(ServiceLocatorInterface $serviceLocator, $name, $requestedName) 
    { 
     $class = '\MyApp\Repository\'.$requestedName; 
     return new $class(); 
    } 
} 

正如您所看到的,您不必爲應用程序中的每個存儲庫服務創建單獨的工廠。