javatemplatesinterfaceprototype-pattern

using template parameters in java interface declaration


I come from C++ and I'm taking a Java class right now, studying design patterns more specifically. Last class, the professor gave us an example project to help us get started with the Prototype pattern and there was an interface declaration in the project which I didn't understand very well (and didn't ask the professor either :/)

package pattern.prototype.impl;

public interface IPrototype<T extends IPrototype> extends Cloneable {

    //clone: Permite realizar una clonacion superficial del prototipo.
    public T clone();

    //deepClone: Permite realizar una clonación profunda del prototipo.
    public T deepClone();
}

could anyone give me some kind of explanation regarding the use of parameter T in this context IPrototype<T extends IPrototype>. What is its purpose there? Is it necessary or just one way of doing it?

Thank you


Solution

  • This is called the "Curiously re-occurring template pattern". As the name suggests, it was discovered for code written in C++ which uses templates, however, the pattern works with Generics in Java as well.

    Here I can implement the interface as follows:

    public class ConcretePrototype implements IPrototype<ConcretePrototype > {
        @Override
        public ConcretePrototype clone() { ... }
    
        @Override
        public ConcretePrototype deepClone() { ... }
    }
    

    Notice the method signature of the overriden methods. The base interface IPrototype does not know about ConcretePrototype, however, by using CRTP we can enforce that ConcretePrototype returns values of its own type.