标签: factory

在Python中使用基类构造函数作为工厂?

我正在使用基类构造函数作为工厂并在此构造函数/工厂中更改类以选择适当的类 - 这种方法是很好的python实践还是有更优雅的方法?

我试图阅读有关元类的帮助,但没有取得很大的成功.

这是我正在做的事情的例子.

class Project(object):
  "Base class and factory."
  def __init__(self, url):
      if is_url_local(url):
        self.__class__ = ProjectLocal
      else:
        self.__class__ = ProjectRemote
      self.url = url

class ProjectLocal(Project):
  def do_something(self):
    # do the stuff locally in the dir pointed by self.url

class ProjectRemote(Project):
  def do_something(self):
    # do the stuff communicating with remote server pointed by self.url
Run Code Online (Sandbox Code Playgroud)

有了这段代码,我可以通过基类Project创建ProjectLocal/ProjectRemote的实例:

project = Project('http://example.com')
project.do_something()
Run Code Online (Sandbox Code Playgroud)

我知道另一种方法是使用将返回基于url的类对象的fabric函数,然后代码看起来类似:

def project_factory(url):
      if is_url_local(url):
        return ProjectLocal(url)
      else:
        return ProjectRemote(url)

project = project_factory(url)
project.do_something()
Run Code Online (Sandbox Code Playgroud)

我的第一种方法是品味问题还是有一些隐藏的陷阱?

python factory

8
推荐指数
2
解决办法
5645
查看次数

什么时候使用工厂模式而不是重载的构造函数来实例化对象更有意义?

在Karl Seguin的编程基础中,有一小部分关于使用工厂模式.他通过声明"你可以使用构造函数重载完成相同的功能"来关闭段落,但是没有说明何时或为什么?

那么,何时使用工厂模式而不是重载的构造函数来实例化对象更有意义呢?

constructor design-patterns factory overloading instantiation

8
推荐指数
1
解决办法
1514
查看次数

Angular js从工厂返回未定义的对象

我有一个控制器和工厂定义如下.

myApp.controller('ListController', 
        function($scope, ListFactory) {
    $scope.posts = ListFactory.get();
    console.log($scope.posts);
});

myApp.factory('ListFactory', function($http) {
    return {
        get: function() {
            $http.get('http://example.com/list').then(function(response) {
                if (response.data.error) {
                    return null;
                }
                else {
                    console.log(response.data);
                    return response.data;
                }
            });
        }
    };
});
Run Code Online (Sandbox Code Playgroud)

令我困惑的是,我从控制器获取未定义的输出,然后控制台输出的下一行是我工厂中的对象列表.我也尝试过将控制器更改为

myApp.controller('ListController', 
        function($scope, ListFactory) {
    ListFactory.get().then(function(data) {
        $scope.posts = data;
    });
    console.log($scope.posts);
});
Run Code Online (Sandbox Code Playgroud)

但我收到错误

TypeError: Cannot call method 'then' of undefined
Run Code Online (Sandbox Code Playgroud)

注意:我通过http://www.benlesh.com/2013/02/angularjs-creating-service-with-http.html找到了有关使用工厂的信息.

ajax factory angularjs angularjs-factory

8
推荐指数
1
解决办法
9367
查看次数

Zend Framework 2中的工厂类与闭包

在Zend Framework 2中使用工厂类或闭包更好吗?为什么?

我知道闭包不能被序列化,但如果你从Module#getServiceConfig()返回它们,这不会影响其余配置数据的缓存,并且闭包将被缓存在你的操作码缓存中.

在构建工厂类与执行闭包时,性能有何不同?PHP是否仅在执行时包装和实例化闭包,或者它是否会在每个请求中为配置文件中定义的每个闭包执行此操作?

有没有人比较过每种方法的执行时间?

也可以看看:

factory php-closures zend-framework2

8
推荐指数
1
解决办法
1475
查看次数

Dart工厂(构造函数)与静态方法; 例如,为什么int.parse()不是工厂构造函数?

飞镖风格指南建议使用构造函数,而不是静态方法来创建实例,因为" 命名的构造函数和工厂构造函数中达特给你所有的其他语言的静态方法的灵活性,同时仍然允许调用点显得像一个普通的构造函数调用 ".

那么是否存在技术原因,因为已经声明int.parse()并且double.parse()是静态方法而不是工厂构造函数?

更一般地说,选择在Dart中通过静态(工厂)方法编写工厂构造函数的指导原则是什么?

constructor static-methods factory factory-method dart

8
推荐指数
1
解决办法
1546
查看次数

C++ 11声明工厂是基类的朋友

我正在尝试为派生类创建一个工厂.我只希望工厂能够创建派生类的实例,所以我已经创建了基础构造函数protected; 派生类只使用基类构造函数,因此它们的构造函数protected也是如此.

我试图将工厂声明为基类的朋友,以便它可以访问protected构造函数.当我使用此命令编译时

clang++ -std=c++11 -stdlib=libc++ Friends.cpp -o Friends
Run Code Online (Sandbox Code Playgroud)

我收到此错误:

Friends.cpp:23:20: error: calling a protected constructor of class 'A'
        return new T(i);
               ^
Friends.cpp:42:16: note: in instantiation of function template specialization 'Create<A>' requested
      here
        A* a = Create<A>(1);
           ^
Friends.cpp:30:25: note: declared protected here
             using Base::Base;
                    ^
Run Code Online (Sandbox Code Playgroud)

与派生类的类似错误一起B.

我从stackoverflow.com上读到其他问题的感觉,这在C++ 11中是不可能的,但我不确定为什么.有人可以解释为什么这不起作用,或许可以替代?

示例代码

#include <iostream>

using namespace std;

// Forward declaration
template<class T> T* Create(int i);

class Base {
    public:
        template<class T>
        friend T* …
Run Code Online (Sandbox Code Playgroud)

c++ inheritance factory friend c++11

8
推荐指数
1
解决办法
1971
查看次数

构造函数注入(DI)与静态工厂的交叉关注问题?

在大多数任意应用中,需要在所有可用层中解决许多交叉问题,例如日志记录,消息总线,配置.我注意到的是,在某些类中,如果使用IoC注入模块,它们往往会完全炸毁构造函数.

public class MyService : IService 
{
    public MyService(ILogger logger, IAppSettings settings, IEventBus eventBus...)
    {

    }
}
Run Code Online (Sandbox Code Playgroud)

对于构造函数过度注入的常见情况,我倾向于将关注点折射成紧密组合在一起的构建块,因此我在类中获得的依赖项更少.但是,对于交叉切割概念,这是不可能的.

在日志框架中,静态工厂/服务似乎非常流行,例如

// Application root
MyLoggerService.SetFactory(log4NetFactory);

// Somewhere
MyLoggerService.GetLogger("name") // returns Log4NetLogger created by Log4NetFactory.
Run Code Online (Sandbox Code Playgroud)

我的问题是:对于各种交叉切割的东西,这种方法是否很好?如果代码最终看起来像这样,有什么缺点:

public class MyService : IService
{

    private readonly IReallyNeedThat _dependency;

    public MyService(IReallyNeedThat dependency)
    {
        _dependency = dependency;
    }

    private readonly ILogger _logger = LoggerService.GetLogger("MyService");
    private readonly IEventBus _eventBus = EventBusService.GetEventBus();
    private readonly IConfiguration _configuration = ConfigurationService.GetConfiguration(Level.Roaming)
    private readonly IExceptionHandler _exceptionHandler = ExceptionPolicy.GetHandler();
    private readonly ITracer _tracer = …
Run Code Online (Sandbox Code Playgroud)

c# design-patterns factory dependency-injection cross-cutting-concerns

8
推荐指数
2
解决办法
1585
查看次数

工厂模式,内存泄漏

我正在阅读Hodges的书"Delphi中的更多编码",关于工厂模式的部分.试着学习东西.把我的代码分解成小单元.我使用ReportMemoryLeaksOnShutDown := True;和停止代码会导致内存泄漏.为什么会发生,我该如何解决?

unit Unit2;

interface

uses
  Generics.Collections, System.SysUtils;

type
  TGatewayTpe = (gtSwedbank, gtDNB);

type
  TBaseGateway = class

  end;

type
  TSwedbankGateway = class(TBaseGateway)
  end;

type
  TGatewayFunction = reference to function: TBaseGateway;

type
  TGatewayTypeAndFunction = record
    GatewayType: TGatewayTpe;
    GatewayFunction: TGatewayFunction;
  end;

type
  TGatewayFactory = class
  strict private
    class var FGatewayTypeAndFunctionList: TList<TGatewayTypeAndFunction>;
  public
    class constructor Create;
    class destructor Destroy;
    class procedure AddGateway(const AGatewayType: TGatewayTpe;
      const AGatewayFunction: TGatewayFunction);
  end;

implementation

class procedure TGatewayFactory.AddGateway(const AGatewayType: TGatewayTpe;
  const AGatewayFunction: TGatewayFunction);

var
  _GatewayTypeAndFunction: TGatewayTypeAndFunction; …
Run Code Online (Sandbox Code Playgroud)

delphi factory factory-pattern delphi-xe2

8
推荐指数
1
解决办法
203
查看次数

AngularJS"恒定"工厂

我正在设置AngularJS中的配置文件.是否可以在AngularJS中创建一个不能覆盖其密钥的工厂?例如,我可以像这样设置一个不能被覆盖的常量

module.constant('animals',{"cat":"meow","dog":"woof"});

但我想做这样的事情,允许覆盖的值,但不允许工厂本身

module.value('catSound','meow')
      .value('dogSound','woof')
      .factory('animals', ['catSound','dogSound', function(catSound, dogSound) {
            return {
                 "cat": catSound,
                 "dog": dogSound
            }
      });
Run Code Online (Sandbox Code Playgroud)

上面的工厂可以被覆盖,允许另一段代码拥有module.factory('animals',function(){ return 7 })并破坏一切.但是,作为工厂,个别值可以(并且应该)可以覆盖,因此我应该能够分配module.value('catSound','hiss')并使事情仍然按预期工作.

我已经尝试过注入常量,但据我所知,这是不可能的.如何防止我的工厂声明被覆盖?我意识到在描述我想要的东西时,常量可能不是正确的术语,但我确实希望工厂的函数定义是恒定的.

configuration factory constants angularjs

7
推荐指数
1
解决办法
4349
查看次数

工厂模式:创建bean时验证输入(Guice/Guava)

我正在编写一个新的应用程序,使用Guice进行依赖注入,以及Guava的属性验证前置条件.

我正在使用工厂模式根据外部输入创建bean.问题是,验证输入的首选方法什么?(在可维护性,清晰度等方面)

我们假设这些类:

Bean.java

public interface Bean {

    public Object getFoo();

}
Run Code Online (Sandbox Code Playgroud)

BeanImpl.java

public class BeanImpl implements Bean {

    private final Object foo;

    public BeanImpl(Object param) {
        foo = param;
    }

    @Override
    public String getFoo() {
        return foo;
    }

}
Run Code Online (Sandbox Code Playgroud)

我想检查"param"是否包含"foo"的有效值:

Preconditions.checkArgument(SomeValidator.isValid(param), "Bad param: %s!", param);
Run Code Online (Sandbox Code Playgroud)

我应该在哪里做,为什么?

  • 在BeanImpl的构造函数中?(我不确定为什么,但在构造函数中添加检查感觉是个坏主意.)
  • 在调用BeanFactory.create(param)之前?(听起来像是可怕的代码重复.)
  • 通过一些我不知道的Guice机制?

java validation factory guice

7
推荐指数
1
解决办法
699
查看次数