Java,C++中如何实现类似使用模板参数的功能,避免创建Creator子类?
In Java, How to implement the functions similar to using the template parameter to avoid creating Creator subclasses in C++?
最近在看"Design Pattern-Elements of Reusable Object-Oriented Software"这本书的时候,书中有这么一段话:
Using templates to avoid subclassing. As we've mentioned, another potential
problem with factory methods is that they might force you to subclass just
to create the appropriate Product objects. Another way to get around this in
C++ is to provide a template subclass of Creator that's parameterized by the
Product class.
我想知道的是:在Java中,如何在C++中实现类似于使用模板参数的功能来避免创建Creator子类?
我尝试过使用泛型,但我不知道如何使用它。
public class ConcreteCreator<T extends Product> extends Creator{
@Override
public Product createProduct() {
// ... how can I return new T();
}
}
// ... how can I return new T();
简单的回答:在 Java 中你没那么容易。
Java 不是 C++,泛型在很多方面不如 C++ 模板强大。
重点是:没有办法"generically"创建一些未知的任意新对象class。您也许可以 通过使用反射、Class.forName()
和 newInstance()
解决 问题,但这通常会以反射为代价:笨拙且容易出错.
当然,您可以 return 一个特定的子 class 类型(和其中的实例),但是您必须为每个此类类型编写一个特定的方法。
您无法实例化 T
。它是一个占位符,将在 运行 时间被删除。而不是 returning Product
你想要 return Product
.
的具体类型
在java中,工厂方法已经有了泛型。这是 Supplier<T>
.
您可能应该使用 Supplier<Product>
而不是 Creator
。
然后,您通常使用 lambda 函数或方法引用来提供实例。
如果你想调用 setCreator(Supplier<Product>)
,例如,你希望它创建你的 MyProduct
子类,那么你只需调用 setCreator(MyProduct::new)
.
Lambda 允许您在不进行子类化的情况下进行更复杂的构造,即使不存在合适的构造函数,如 setCreator(() -> new MyProduct(CONST_VAL_1, UtilityClass.getCurrentValue2());
最近在看"Design Pattern-Elements of Reusable Object-Oriented Software"这本书的时候,书中有这么一段话:
Using templates to avoid subclassing. As we've mentioned, another potential problem with factory methods is that they might force you to subclass just to create the appropriate Product objects. Another way to get around this in C++ is to provide a template subclass of Creator that's parameterized by the Product class.
我想知道的是:在Java中,如何在C++中实现类似于使用模板参数的功能来避免创建Creator子类?
我尝试过使用泛型,但我不知道如何使用它。
public class ConcreteCreator<T extends Product> extends Creator{
@Override
public Product createProduct() {
// ... how can I return new T();
}
}
// ... how can I return new T();
简单的回答:在 Java 中你没那么容易。
Java 不是 C++,泛型在很多方面不如 C++ 模板强大。
重点是:没有办法"generically"创建一些未知的任意新对象class。您也许可以 通过使用反射、Class.forName()
和 newInstance()
解决 问题,但这通常会以反射为代价:笨拙且容易出错.
当然,您可以 return 一个特定的子 class 类型(和其中的实例),但是您必须为每个此类类型编写一个特定的方法。
您无法实例化 T
。它是一个占位符,将在 运行 时间被删除。而不是 returning Product
你想要 return Product
.
在java中,工厂方法已经有了泛型。这是 Supplier<T>
.
您可能应该使用 Supplier<Product>
而不是 Creator
。
然后,您通常使用 lambda 函数或方法引用来提供实例。
如果你想调用 setCreator(Supplier<Product>)
,例如,你希望它创建你的 MyProduct
子类,那么你只需调用 setCreator(MyProduct::new)
.
Lambda 允许您在不进行子类化的情况下进行更复杂的构造,即使不存在合适的构造函数,如 setCreator(() -> new MyProduct(CONST_VAL_1, UtilityClass.getCurrentValue2());