I'm currently working on a student project and wondering if there is a way to create objects exclusively with factory methods?
public class PersonFactory {
public static Person createPerson() {
// some constraints ...
return new Person();
}
}
My exemplary PersonFactory.java
is supposed to return Person
objects with its createPerson()
method.
public class Person {
// some examples ...
private String name;
private int age;
public Person() {
// ...
}
}
This works fine, but in the main
program, I am still able to create Person
objects with their common constructor (since it is public
). But if I change the constructor to private
, the factory method cannot access it either.
public class PersonManagement {
public static void main(String[] args) {
// both still works ...
Person p1 = new Person();
Person p2 = PersonFactory.createPerson();
}
}
Thank you so much in advance ;)
The factory method is a creational design pattern, i.e., related to object creation. In the Factory pattern, we create objects without exposing the creation logic to the client and the client uses the same common interface to create a new type of object.
Advantage of Factory Design Pattern Factory Method Pattern allows the sub-classes to choose the type of objects to create. It promotes the loose-coupling by eliminating the need to bind application-specific classes into the code.
If we notice the name Factory method, that means there is a method which is a factory, and in general, factories are involved with creational stuff and here with this, an object is being created. It is one of the best ways to create an object where object creation logic is hidden from the client.
Factory classes are often implemented because they allow the project to follow the SOLID principles more closely. In particular, the interface segregation and dependency inversion principles.
You can make the Person
constructor package private (i.e. remove the public
access modifier), which will only allow classes from the same package to access it.
Then, if PersonFactory
belongs to the same package as Person
, it would have access to that constructor.
If PersonManagement
belongs to a different package, it won't have access to that constructor.
Another option is to keep the Person
constructor private
and move the createPerson()
method to the Person
class.
I usually solve the problem by putting the factory method in the Person
class rather than in a separate factory class. In this case the constructor can be private, and Person
objects can be obtained from the factory method and nowhere else. Don’t know whether that could fit into your design, though.
One potential issue here would be if you didn’t want your factory method static
. However, I see that yours is, so this shouldn’t stop you.
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