I am relatively new to Java and Design patterns. I am trying to implement the Builder pattern for my application. I have an interface
which has a method build
this build
method will take the class as a parameter and return the same.
public interface TestInterface {
public TestInterface withTest(int start);
public <T> T build();
}
As of now, I have implemented this interface
within a single class and overriding the methods in the GenerateBuilder
class and it works fine
public class GenerateNumbers {
private String start;
private GenerateGSRN(GenerateBuilder builder) {
this.start = builder.start;
}
public static class GenerateBuilder implements TestInterface {
private String start;
@Override
public TestInterface withGcp(String start) {
this.start = start;
return this;
}
@Override
public GenerateNumbers build() {
return new GenerateNumbers(this);
}
}
}
But I want to move the GenerateBuilder
class which is overriding the methods to its own separate class so that it can be used by any other class (make it as common so I do not have to write this code again).
But as we can see the GenerateBuilder
Build
function is tightly coupled to GenerateNumbers
due to which I am unable to move it. I want to change the Build
method in Interface
as well as during the overriding
so that it will return the instance of the class to calling class.
For example: If GenerateNumbers
is calling build method then build
method should return GenerateNumbers
. If GenerateNumbersRandom
is calling then build
method should return instance of GenerateNumbersRandom
.
I tried couple of things but did not work:
In interface:
public <T> T build(Class clazz);
In the override:
@Override
public <T> T build(Class clazz) {
return clazz.newInstance();
}
I hope I was able to explain the problem properly. Can someone please suggest me how to make this work.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…