2014-10-09 27 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(); 
    } 
} 

正如您所看到的,您不必为应用程序中的每个存储库服务创建单独的工厂。