-1

How can I make a single instance of this class without singleton and how can I declare it so another class can access it without declaring it globally?

Please read the codes (especially the comments) for a better understanding:

#include <iostream>
#include <vector>

// The only class that will be using this class is Obj...
// There can only be a single instance of ObjManager but how can I do that
// without singleton???
class ObjManager
{
    friend class Obj;
    int i;
};

// Since I cannot think of a better way of accessing the SAME and ONLY ObjManager, I
// have decided to declare a global instance of ObjManager so every instance of
// Obj can access it.
ObjManager g_ObjManager;

class Obj
{
    friend class ObjManager;
public:
    void Set(int i);
    int Get();
};

void Obj::Set(int i) {
    g_ObjManager.i += i;
};

int Obj::Get() {
    return g_ObjManager.i;
};

int main() {
    Obj first_obj, second_obj;

    first_obj.Set(5);
    std::cout << second_obj.Get() << std::endl; // Should be 5.
    second_obj.Set(10);
    std::cout << first_obj.Get() << std::endl; // Should be 15.

    std::cin.get();
    return 0;
};
  • 2
    There is no obvious reason you don't need a God object. God is between the chair and the monitor when you are a programmer, you can't pass the job to somebody else. – Hans Passant Oct 10 '13 at 22:48
  • Isn't this the whole point of the Singleton pattern? Why would you want to do it without that? – Barmar Oct 10 '13 at 22:50
  • With what you are doing, you can accomplish the same thing with a static member. – Zac Howland Oct 10 '13 at 22:50

2 Answers2

1

Why not something like:

class ObjManager
{
private:
    ObjManager() {} 

public:
    static ObjManager& get() {
        static ObjectManager m;
        return m;
    }
    friend class Obj;
    int i;
};

Then just call ObjManager::get to get the reference. As a bonus, it will only be constructed if you actually use it. It's still a singleton, but it's a bit better than a global (in my opinion).

user1520427
  • 1,345
  • 1
  • 15
  • 27
0

If you want all Obj instances to share the same ObjManager instance (and you don't want to use the Singleton pattern to create the Obj's using the ObjManager), you can create a static member of ObjManager in Obj:

class ObjManager { ... };

class Obj
{
private:
   static ObjManager manager;
};

Then when you create an instance of Obj, it will share the same ObjManager with all other instances.

Zac Howland
  • 15,777
  • 1
  • 26
  • 42