In Java, How to implement the functions similar to using the template parameter to avoid creating Creator subclasses in C++?

factory method pattern
abstract factory design pattern
builder design pattern
abstract factory design pattern in java
design patterns
factory pattern with parameterized constructor
factory method example
creational design patterns

Recently, when I was reading the book named "Design Pattern-Elements of Reusable Object-Oriented Software", there was such a paragraph in the book:

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.

what I want to know is: In Java, How to implement the functions similar to using the template parameter to avoid creating Creator subclasses in C++?

I have tried to use generics, but I don't know how to use it.

public class ConcreteCreator<T extends Product> extends Creator{

    @Override
    public Product createProduct() {
        // ... how can I return new T();

    }
}

In java, there is already a generic type for factory methods. It's Supplier<T>.

You should probably use Supplier<Product> instead of your Creator.

Then, you typically use a lambda function or method reference to supply an instance.

If you want to call setCreator(Supplier<Product>), for example, and you want it to create your MyProduct subclass, then you just call setCreator(MyProduct::new).

Lambdas allow you to do more complex constructions without subclassing, even when an appropriate constructor doesn't exist, like setCreator(() -> new MyProduct(CONST_VAL_1, UtilityClass.getCurrentValue2());

Replace Constructor with Factory Method, Solution: Create a factory method and use it to replace constructor calls. that does something more than just setting parameter values in object fields. Java C#PHPPythonTypeScript this refactoring technique is related to Replace Type Code with Subclasses. C# � C++ � Java � PHP � Python � Ruby � Swift � TypeScript. This pattern is widely used in the Java core libraries, for example by java.util.AbstractList, or java.util.AbstractSet. For instance, Abstract List provides a skeletal implementation of the List interface. An example of a template method can be the addAll() method, although it's not explicitly defined as final:

// ... how can I return new T();

Simple answer: you can't that easily in Java.

Java isn't C++, and generics are in many ways less powerful than C++ templates.

The point is: there is no way to "generically" create new objects of some unknown arbitrary class. You might be able to work around that by using reflection, and Class.forName() and newInstance(), but that comes at the usual cost of reflection: it is clumsy and errorprone.

Sure, you can return a specific subclass type (and instance there), but then you have to write a specific method for each such type.

Factory Method, Also, the factory method in the base class should have its return type declared as However, the primary function of the company as a whole is still writing code, not This example illustrates how the Factory Method can be used for creating The creator's subclasses // usually provide the implementation of this method. If a generic method appears inside a generic class, it's a good idea to avoid using the same names for the type parameters of the method and class, to avoid confusion. The same applies to nested generic classes.

You can not instantiate T. It is a placeholder which will be erased on run time. Instead of returning the Product you want to return the concrete type of Product.

Factory Method Design Pattern, Factory Method lets a class defer instantiation to subclasses. People often use Factory Method as the standard way to create objects; but it isn't Factory Method is similar to Abstract Factory but without the emphasis on families. of factory method is: a static method of a class that returns an object of that class' type. • A class wants its subclasses to define the specific types of objects that it cre-ates. From this description the factory method pattern appears similar to the template method pattern. It is very similar save that the factory method is creational while the template method is behavioral in nature. Factory Methods have four (4) participants:

4. The Factory Pattern: Baking with OO Goodness, There is more to making objects than just using the new operator. It's times like these that you can fall back on OO Design Principles to look for clues. a class that implements a Java interface, by using the 'implements' keyword in the going to have a subclass for each regional type (NYPizzaStore, ChicagoPizzaStore,� Generics in Java is similar to templates in C++. The idea is to allow type (Integer, String, … etc and user defined types) to be a parameter to methods, classes and interfaces. For example, classes like HashSet, ArrayList, HashMap, etc use generics very well. We can use them for any type. Generic Class

Factory method pattern, This Java example is similar to one in the book Design Patterns. The MazeGame uses Rooms but it puts the responsibility of creating Rooms to its subclasses� For example, a method that operates on numbers might only want to accept instances of Number or its subclasses. This is what bounded type parameters are for. To declare a bounded type parameter, list the type parameter's name, followed by the extends keyword, followed by its upper bound, which in this example is Number.

OOP Inheritance & Polymorphism - Java Programming Tutorial, A Book is written by one Author - Using an "Object" Member Variable We need an Author instance to create a Book instance Author ahTeck = new Author("Tan In OOP, we often organize classes in hierarchy to avoid duplication and reduce redundancy. In Java, you define a subclass using the keyword " extends ", e.g., Firstly u need to understand that GENERIC in java represents a General Model( be it a method or a class). Secondly, by creating generic class u r creating a General Class which can operate on any type of Object. Thirdly, without using generics u need to create separate class for supporting various types of objects.

Comments
  • You cannot do it directly as You mentioned (@GhostCat explained it in detail). But generally, if You need to do it this way, there is a big chance that Your class structure was wrongly designed or uses some anti-pattern.