design pattern for global object access

Hi,

I'm creating an application in an object oriented way. What I would like, is to have a global container of objects with the same type. I know this could be achieved by using a vector, a linkedlist, ...

But my knowledge of these structures doesn't go as far as OO design.

The purpose of this vector would be to have it available in every other class. Be it to read from it, write to it, edit, ...

The only solution that comes to mind is using a static globally declared vector in my main class. But doesn't this harm the rules of encapsulation? Or would this be an exception? Is there another (better) way to achieve this?

Create the global container as a singletone object. Only one instance of it will be available at any time. Now anyone using it will work only on one instance. If multi-threaded you will have to restrict the access on this single instance. Create this container from main class.
Agreed, the Singleton pattern provides two main benefits: it places restrictions on object creation (for example, limiting the number of instances to only one) and it provides an easy way to access its instance(s).
I've been looking into the singleton pattern and was a not convinced to use it since it is seen as a pattern which still goes a step back from object oriented design. Now, if there is no better way, I will be using a singleton. But I was just wondering.
The singleton design pattern does tend to get frowned upon by OO purists, but they do indeed have some good reasons for frowning upon it.

Usage of the singleton pattern usually indicates some problem with the overall application design.

Instead of a global object, why not just a high level object that encapsulates your vector and all the objects that need access to it, as well as the interface between those objects and your vector?

Another option would be to pass a reference to your container to all the classes that need access to it.

Also, one question that should always be asked in these situations is why does this vector need to be available in every other class, and can your class hierarchy be refactored to eliminate this need?

One of the dangers of globals is that you have no control over who has access to it. With a Singleton, you have a global with an interface you control, so you at least control HOW that global gets accessed, but you still have no control over who has access to it.
Topic archived. No new replies allowed.