I came across this type of code recently:
final class OnlyMe {
private int a;
private int b;
//setter and getters for a and b.
private OnlyMe(){}
public static OnlyMe getOnlyMeObj(int c) {
// use c value to connect to database
// to populate a and b
if(rs.next()) {
OnlyMe onlyMe = new OnlyMe();
onlyMe.a = rs.getInt(1);
onlyMe.b = rs.getInt(2);
return onlyMe;
}
// return null for everything else.
// assume the code is under try-catch block.
return null;
}
So, its seems like the 'getOnlyMeObj(int)' could be extracted out to another class. But it seems like the developer wanted this class to be only created by that method depending upon the input to that method.
What would be a reason for that?
Is this some type of pattern or anti-pattern or no pattern?
Is there a better solution?
This is a static factory pattern. The idea is to create instances of an object via a static (class-level) method and return it. There are several possible uses of this pattern:
see: see: https://www.youtube.com/watch?v=sOpbAOX5nJs
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With