0

I have 2 singleton services, each of them must have a 'context' field, but this field must be represented as the same object for both singletons. Also, access to this object must be limited by these singletons. Further, there is a chance that I will add the third singleton service with this field, and that one must be represented with the same object too. My first approach was smth like this:

abstract class Abs {
   protected static Object context = new Object();
   // some static methods
}
class Service1 extends Abs {}
class Service2 extends Abs {}

But I'm not sure that it is a good solution.

Sandro700
  • 3
  • 1
  • I see only one problem: if _context_ can be mutated from _Service1_ and _Service2_, then it will become difficult to trace issues, because – as an example – _Service1_ could mutate _context_ and trust that _context_ remains unchanged but _Service2_ could mutate it any given point of time. If _context_ resp. all its properties are immutable, then I do not see problems with your solution. – lukas.j Dec 06 '21 at 12:25
  • A class that only has static members isn't really a class, inheritance is usually bad, and singleton is an anti-pattern. So no, not good practice. A better approach would be a factory that instantiates the two services, and constructs each with a common context. Context can be a private instance field of each service. Much better for unit testing, because it's easy to test a service by injecting a mock/stub/fake context. – Michael Dec 06 '21 at 12:26
  • Thx for your answers – Sandro700 Dec 06 '21 at 13:13
  • Good practice == Bad practice == opinion. – Stephen C Dec 06 '21 at 13:19
  • Yet another *alternative* solution is to declare the class as `final` and declare its only constructor as `private`. That prevents creation of subclasses AND creation of (unwanted) instances. (But it doesn't address the testability issue.) – Stephen C Dec 06 '21 at 13:20

0 Answers0