Suppose I have a class called Factory. I intend to have that class publicly accessible so anyone can create and access the factory. I want the factory to create and distribute widgets. I only want the factory to be able to create widgets, not anyone in the public program space. However, I’d like to have a method called distribute() that would give out a widget to the main program. At that point the main program could access all the public methods of that widget. It could also give it back to the factory if need be, thereby removing any public access to that object.
If this is possible, how does one accomplish this?
What you’re looking for is an inner class. By declaring the constructor of the inner class private, only the encapsulating class can access it! Then you create a factory method in the outer class to build the widget and distribute it. I’ve declared it
statichere, but that’s not necessary, depending on your needs.Note that in clean code your other concerns must be addressed by being careful about your referential integrity. To ‘give back’ the widget all other references to it must be released. Your Factory can certainly keep track of what widgets it’s given out, but it’s very hard to ‘recall’ widgets reliably.