public class A {
private A(int param1, String param2) {}
public static A createFromCursor(Cursor c) {
// calculate param1 and param2 from cursor
return new A(param1, param2);
}
}
Is there a design pattern for this kind of construction code? If so, what’s the purpose of this pattern? Why not just use:
// calculate param1 and param2 from cursor
new A(param1, param2);
So, to sum up.
That pattern is called Static Factory Method and it’s described for example here: How to use "Static factory methods" instead of constructors?
In simplest form it looks like this:
Your example is little bit more complex as it includes computing parameters for invoking constructor
The purpose of using such way for creating new object may be the need to repeat those calculating every time before calling
new A(params)directly. So it’s just avoiding repeating yourself, and simplest way to achieve this is creating a method.Furthermore using the same way, you can provide even more options to create
new A. For example you can change the way your calculation works with:Then you may pass the same parameter to this method, and result will be different (coz method name is varies).
And of course you can create your
new Afrom any other parameter, using the same constructor as before:So you have much more possibilities with Static Factory Methods than with simple usage of constructors only.