标签: factory

C# 泛型工厂方法

也许这是一个简单的 C# 新手问题,但就这样吧 — 这将是我与其他问题的一次全新突破,这些问题非常困难,以至于没有人知道答案。:)

假设我有一个 C# 泛型类型:

Thing<T>
Run Code Online (Sandbox Code Playgroud)

假设我想使用静态工厂方法来制作一个东西。在 Java 中,这没有问题:

public static <T> Thing<T> createThing()
{
  return flag ? new Thing<Integer>(5) : new Thing<String>("hello");
}
Run Code Online (Sandbox Code Playgroud)

我如何在 C# 中执行此操作?谢谢。

c# generics factory

5
推荐指数
1
解决办法
1万
查看次数

C++ 构造函数和计算域

在 C++ 中,构造函数必须const使用初始化列表来初始化变量。

如果我的构造函数需要计算这些字段的值怎么办?通过数据库查找或简单计算进行说明。

这里可以应用工厂模式,但是看起来有点重。我正在考虑这样的静态方法X::GetX(param1, param2)将计算值并调用私有构造函数。

是否有更好或更流行的模式可以在这里使用?

c++ constructor factory

5
推荐指数
1
解决办法
596
查看次数

工厂设计模式如何处理不同长度的构造函数?

我想要一个类,它根据我传递的字符串创建不同类型的对象。根据我的研究,这最好地描述了工厂设计模式。我成功地实现了它,但遇到了一个设计问题:我不知道如何创建具有不同长度构造函数的对象。

我们以一个名为 Pet 的抽象父类为例。其中有 3 个孩子:鱼、猫和狗。它们都继承了 Pet 的重量和颜色,因此它们都包含在它们的构造函数中。但是一条鱼可能需要多个鳍和一个关于它是否是咸水鱼的布尔值。这是一个 4 参数构造函数。猫想要腿的数量。那是3个参数。狗可能有腿、品种以及是否与其他狗相处良好等 5 个参数。

在 C++ 中,我知道没有任何反射,因此最常见的做法似乎只是声明一个字符串到函数指针的映射,其中函数指针指向一个如下所示的函数:

    template<typename T> Pet* createObject(int weight, std::string color) {return new T(weight, color);}
Run Code Online (Sandbox Code Playgroud)

同样,我不确定如何在调用中填充更多参数而不影响其他对象构造函数的调用。

我可以想到两种解决方法:创建新函数来接受不同数量的参数,或者为构造函数创建超过一定大小的默认参数。

解决方法 1 似乎有点过多,具体取决于我有多少个不同的参数大小。

解决方法 2 似乎忽略了构造函数的全部要点,因为我将被迫在调用构造函数后分配数据。

还有其他更好的解决方法吗?

c++ factory

5
推荐指数
1
解决办法
1051
查看次数

是否可以在 TypeScript 中声明和调用函数字典?

我正在做一些重构,想知道是否可以声明和初始化工厂函数的字典,以枚举器为键,以便它可以用作随后可以调用的工厂函数的查找?或者,我是否走错了路,错过了一个更优雅的解决方案。我按照这个答案声明并初始化了一个类型化字典,但我不确定我是否声明了签名正确,例如键是数字,值是函数。我已经将我的代码简化为一个非常通用的示例 - 我知道它相当做作,但这样的意图更加清晰。

// Types are enumerated as I have several different lists of types which I'd like to
// implement as an array of enumerators
enum ElementType {
    TypeA,
    TypeB,
    TypeC
}

// Here, I'm trying to declare a dictionary where the key is a number and the value is a
// function
var ElementFactory: { [elementType: number]: () => {}; };

// Then I'm trying to declare these factory functions to return new objects
ElementFactory[ElementType.TypeA] = …
Run Code Online (Sandbox Code Playgroud)

dictionary enumeration factory function typescript

5
推荐指数
1
解决办法
6393
查看次数

如何动态生成bean列表

海伊

我正在寻找一种“简化”/缩短我的弹簧配置的方法。我有这个通用服务,看起来像:

public class GenericService<T> {
   private Class<T> targetClass;
   public void setTargetClass(Class<T> targetClass) {this.targetClass = targetClass;}
   public void doSomething() {...}
}
Run Code Online (Sandbox Code Playgroud)

在我的 spring-config.xml 文件中

<bean id="entity1Service" class="GenericService">
   <property name="targetClass" value="model.Entity1" />
</bean>

<bean id="entity2Service" class="GenericService">
   <property name="targetClass" value="model.Entity2" />
</bean>

...
Run Code Online (Sandbox Code Playgroud)

我正在尝试建立一个工厂来为我构建所有这些服务,以便我可以在 spring-config.xml 中编写类似的内容

<bean class="ServiceFactory">
   <property name="targets">
      <list>
        <value>model.Entity1</value>
        <value>model.Entity2</value>
      </list>
    </property>
</bean>
Run Code Online (Sandbox Code Playgroud)

这将生成 2 个 bean(一个名为entity1Service,另一个名为entity2Service)。得到它?

我该如何开始?我看过 BeanFactory (不要与 FactoryBean 混淆!),但没能明白如何连接所有东西。

如果我的工厂可以扫描我的包并在找到实体时生成服务(通过注释或接口实现),那就更好了,有点像 spring-data 中的 @EnableJpaRepositories 注释对所有 JpaRepository 接口所做的那样。

感谢您提供任何见解、示例、指示...

w。

java configuration spring factory spring-data

5
推荐指数
1
解决办法
8141
查看次数

具有实例化模板的切换枚举的工厂

我在代码库的各个位置都有以下层次结构模式:

enum DerivedType {
    A, B, C };

class Base {
public:
  static Base* Create(DerivedType t);
};

template <DerivedType T>
class Derived : public Base {
};
Run Code Online (Sandbox Code Playgroud)

该方法返回类、或 Create的新对象,具体取决于其参数:Derived<A>Derived<B>Derived<C>

Base* Base::Create(DerivedType t) {
  switch (t) {
  case A: return new Derived<A>;
  case B: return new Derived<B>;
  case C: return new Derived<C>;
  default: return NULL;
  }
}
Run Code Online (Sandbox Code Playgroud)

问题是有很多这样的层次结构,基本上到处都有Base -> Derived相同的复制粘贴实现。Create()有没有一种优雅且易于理解的方法来避免重复?

c++ templates design-patterns factory c++03

5
推荐指数
1
解决办法
1292
查看次数

Python子类工厂

我有一个父类的多个子类,并且想要根据序列化数据中的字符串实例化它们。我的方法是将实例化字符串映射到类,然后使用工厂方法创建相应的对象:

class Superclass:
    @classmethod
    def get_instance(cls, string):
        return CLASSMAP[string]()

    def name(self):
        pass

class Foo(Superclass):
    def name(self):
        return "my name is Foo"

class Bar(Superclass):
    def name(self):
        return "i'm Bar"

class Baz(Superclass):
    def name(self):
        return "i am called Baz"

CLASSMAP = {
    'foo': Foo,
    'bar': Bar,
    'baz': Baz,
}
Run Code Online (Sandbox Code Playgroud)

我不喜欢将 CLASSMAP 作为全局字典,但我无法在声明中将其定义为超类的成员,因为子类尚未定义(当然,它们必须在超类之后定义) 。我当然可以随后将类映射分配给类:

Superclass.CLASSMAP = {...}
Run Code Online (Sandbox Code Playgroud)

并让超类的 get_instance() 方法引用尚不存在的字段,但它似乎更笨重并且容易出错。

整个模式是否有更 Pythonic 的方法?

python factory class

5
推荐指数
1
解决办法
2955
查看次数

通用接口工厂

我有一个界面:

public interface Handler<E extends Event> {
    void handle(E event);
}
Run Code Online (Sandbox Code Playgroud)

以及它的两个实现:

public class SignupEventHandler implements Handler<SignupEvent> {
    @Override
    public void handle(SignupEvent event) {}
}
Run Code Online (Sandbox Code Playgroud)

public class SignoutEventHandler implements Handler<SignoutEvent> {
    @Override
    public void handle(SignoutEvent event) {}
}
Run Code Online (Sandbox Code Playgroud)

请注意,Event它本身是一个接口,由SignupEvent和实现SignoutEvent

我想知道为Handler.

public class HandlerFactory {
    public static Handler<? extends Event> getHandler(Event event) {
        if(event.type().equals("SignupEvent")) {
            return new SignupEventHandler();
        } else if(event.type().equals("SignoutEvent")) {
            return new SignoutEventHandler();
        } else {
            throw new IllegalArguementException("Unrecognised event …
Run Code Online (Sandbox Code Playgroud)

java factory

5
推荐指数
1
解决办法
80
查看次数

键入 React 组件工厂函数

鉴于类型

type EnumerableComponentFactory = <C, I>(config: {
  Container: React.ComponentType<C>;
  Item: React.ComponentType<I>;
}) => React.FC<{ items: I[] }>;
Run Code Online (Sandbox Code Playgroud)

具有以下实现

const Enumerable: EnumerableComponentFactory =
  ({ Container, Item }) =>
  ({ items }) =>
    (
      <Container>
        {items.map((props, index) => (
          <Item key={index} {...props} />
        ))}
      </Container>
    );
Run Code Online (Sandbox Code Playgroud)

和预期用途

const UnorderedList = Enumerable({
  Container: ({ children }) => <ul>{children}</ul>,
  Item: ({ title }: { title: string }) => <li>{title}</li>,
});

<UnorderedList items=[{title: "Something"}] />
Run Code Online (Sandbox Code Playgroud)

我观察到以下 TypeScript 错误

Type '{ children: Element[]; }' is not …
Run Code Online (Sandbox Code Playgroud)

factory type-constraints typescript reactjs tsx

5
推荐指数
1
解决办法
221
查看次数

如何隐藏提供公共静态工厂方法的 Java 记录上的构造函数?

我用Java有这个简单的记录:

public record DatePair( LocalDate start , LocalDate end , long days ) {}
Run Code Online (Sandbox Code Playgroud)

我希望所有三个属性 ( startend、 & days) 都可供公开阅读,但我希望第三个属性 ( days) 自动计算,而不是在实例化期间传入。

所以我添加一个静态工厂方法:

public record DatePair( LocalDate start , LocalDate end , long days ) {}
Run Code Online (Sandbox Code Playgroud)

只想使用这个静态工厂方法进行实例化。我想隐藏构造函数。因此,我显式地编写了隐式构造函数,并对其进行了标记private

public record DatePair( LocalDate start , LocalDate end , long days )
{
    public static DatePair of ( LocalDate start , LocalDate end )
    {
        return new DatePair ( start , end …
Run Code Online (Sandbox Code Playgroud)

java constructor factory static-factory java-record

5
推荐指数
1
解决办法
1389
查看次数