Creating objects exclusively with Factory

I am currently working on a student project and am wondering if there is a way to create objects exclusively using factory methods?

public class PersonFactory { public static Person createPerson() { // some constraints ... return new Person(); } } 

My example PersonFactory.java should return Person objects using the createPerson() method.

 public class Person { // some examples ... private String name; private int age; public Person() { // ... } } 

This works fine, but in the main program, I can still create Person objects with their common constructor (since this is public ). But if I changed the constructor to private , the factory method will also not be able to access it.

 public class PersonManagement { public static void main(String[] args) { // both still works ... Person p1 = new Person(); Person p2 = PersonFactory.createPerson(); } } 

Thank you very much in advance;)

+5
source share
4 answers

I usually solve the problem by putting the factory method in the Person class, and not 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. I don’t know if this can fit into your design.

One potential problem here would be if you didn't need your factory static method. However, I see that yours, so this should not stop you.

+3
source

You can make the Person constructor private (i.e. remove the public access public ), which will allow access to them from only one package.

Then, if PersonFactory belongs to the same package as Person , it will have access to this constructor.

If PersonManagement belongs to another package, it will not have access to this constructor.

Another option is to keep the Person constructor private and move the createPerson() method to the Person class.

+6
source

With the concept of Java visibility, you cannot do much. You can remove public from the constructor of Person , then only these classes in one package Person (and subclasses of Person ) can access the constructor. If PersonManagement is in another package, it will not be able to access the constructor.

Another way would be to make Person an inner class of PersonFactory (or vice versa), then the private constructor should also work, and no one from the outer class will be able to access it.

+1
source

Thanks a lot, this really solved my problem:

 public class Person { // some examples ... private String name; private int age; private Person() { } public static Person createPerson() { // some constraints ... return new Person(); } } 

And main works very well:

 public class PersonManagement { public static void main(String[] args) { Person p1 = Person.createPerson(); // not possible anymore ... Person p2 = new Person(); } } 
0
source

Source: https://habr.com/ru/post/1261974/


All Articles