I am in the middle of writing a small structure to serve as a framework for handling the 2D GUI of a Unity3d project. I have one empty gameobject called "UIManager" with "UIManager" script on it. UIManager is a Singleton with DontDestroyOnLoad. Now here is a problem, it works for all practical purposes but design wise, i am openly revealing my implementation (that it is a singleton) to the rest of the world/project. I need suggestion on how it could be improved such that it is better encapsulated.
For a better design of the problem, I stumbled upon Service Locator Pattern. Now I am even more confused. If i am understanding it correctly, I still declare my UIManager as singleton, but instead of getting it's reference via something like UIManager.GetInstance()... I create another Singleton of "ServiceLocator" and ask it for an instance of UIManager. I don't see how it improves the encapsulation of my UIManager class, whose implementation still remains public. And I don't see how it helps with decoupling.
Any insight into the issue? How do you prefer to do it?
If you want to preserve the access, then remove the public static reference. If you need it because your framework depends on it then maybe it is meant to be public.
You can also make your project a full assembly so your public member can be internal and only accessible from within the assembly.
You could also have your object to use interface to minimize the content accessible.
public interface IFirst{ void GetFirstThing(); }
public interface ISecond { void GetSecondThing(); }
public class MyClass:MonoBehaviour, IFirst, ISecond
{
public void GetFirstThing(){}
public void GetSecondThing(){}
}
public class ConsumerForFirstOnly
{
private IFirst first = null;
public ConsumerForFirstOnly(IFirst first)
{
this.first = first;
}
}
Now your ConsumerForFirstOnly is not aware of the ISecond part of the class.