2

Should i use singleton pattern for MongoDB. I'm currently building an Game Server for turnbase game using Photon Engine and MongoDB.

public sealed class GSEntities
{
    #region Fields
    public IMongoClient Client;
    public IMongoDatabase Database;

    private static GSEntities _instance;
    private static readonly Object sync = new object();

    public static GSEntities Instance
    {
        get
        {
            if (_instance == null)
            {
                lock (sync)
                {
                    if (_instance == null)
                        _instance = new GSEntities();
                }
            }
            return _instance;
        }
    }
}

It's good or should i use other pattern like Repository ?

Thanks for your helps ! :)

1 Answers1

2

It's good or should i use other pattern like Repository ?

Generally speaking, you should use patterns when you need them. Not when you have the time, or it seems cool or it would not hurt.

So ask yourself, do you need a singleton? My guess is no. This could as well be a normal class that you happen to have only one instance of.

Do you need a repository pattern? My guess would be no as well. The description says:

Mediates between the domain and data mapping layers using a collection-like interface for accessing domain objects.

Only you can decide. Again, implement when needed, not when you feel like it or others think it's cool.

nvoigt
  • 75,013
  • 26
  • 93
  • 142