I am implementing a program which uses a shared utility class with singleton behavior.
One instance of the utility class is created in the main thread and passed to all other objects instantiated:
SomeUtil util = new SomeUtil();
...
Foo foo = new Foo(util, arg1, arg2)
Bar bar = new Bar(util, arg3, arg4, arg5)
Is there some more elegant way of achiving this (i.e. design pattern)?
As others have mentioned, Singleton can be an alternative. Note though that your current design is easy to unit test (since you are injecting the
SomeUtildependency, which can thus easily be replaced by a mock object during unit tests), while Singleton makes unit testing awkward and difficult:That being said, if it is a real utility class, i.e. it has no internal state, and it is not dependent on anything which would make unit testing difficult (like a DB, or file system), it can be OK to use it as a Singleton (although this begs the question why do you need to instantiate it at all – usually utility classes have only static methods, and a private constructor to prevent instantiation).