mardi 9 février 2021

How to solve problem when singleton class depends on classes that instantiate during runtime?

To make this general, lets say i have classes A,B,C that needs to call specific method on singleton class S. Classes A,B,C needs to have default constructor, so i can not change it. I have implemented this so far this way: S has static methods and private constructor, which makes it singleton, and A,B,C calls that static methods whenever needed.

BUT

That singleton class S, needs to have instance of class E inside of it, which will be created somewhere in a program.

I was thinking about adding static .setE(E e) method to S, which will be called before classes A,B,C will need to call methods on S and right after class E was instantiated. This is not right approach, because i need to call .setE(E e) explicitly. This way, encapsulation principle will be little damaged, because A,B,C would have also access to .setE(E e) method.

I am looking for a solution that will be more "right" keeping all OOP principles.

I am doing this in Java.

Aucun commentaire:

Enregistrer un commentaire