0

I have in my project two classes for managing memory: MemoryStorage and MemoryFile.

The first works similar to a HDD and keeps MemoryFiles (files, directories, etc.) by using a singleton (add, remove, free, etc). The second works like fstream, but for memory (open, close, write, read, etc.).

Use Example

MemoryFile file(&MemoryStorage);
// Open file in write mode
if (file.open("filename", open_mode::out)) {
    // Data file
    int* obj = new int;
    *obj = 0;
    // Write in internal buff
    file.write(obj, sizeof(int));
    delete obj;
    // Put buff in MemoryStorage and clear buff
    file.close();
}
// Other moment
// Open file in read mode
if (file.open("filename", open_mode::in)) {
    // Data file
    int* obj = new int;
    // Write in internal buff
    file.read(obj, sizeof(int));
    cout << *obj << endl; // Print: 0
    delete obj;
    // Put buff in MemoryStorage and clear buff
    file.close();
}

If I don't use a singleton, creating files with the same name in memory will be possible, leading to an inconsistent file system.

I've read several articles in stack overflow like this one that talk about how singleton is bad pattern according to many programmers.

How else do I resolve the programming problem above without a singleton pattern? Do I use a private static member in MemoryStorage that replicates the effect of a singleton?

Community
  • 1
  • 1
Bill Rock
  • 33
  • 7

2 Answers2

0

Regardless of your use case, if you are absolutely sure, that the object you are representing have one and only one instance in real world, such as the memomy manager, using singleton is certainly a reasonable option.

The problem with singleton is, that it is not as simple pattern as it looks like. To name a few questions you will face - What about multithreaded environment, can you absolutely guarantee not two singletons will be created? And What about destruction of singletons? What about inheritance, or having more singletons?

I suggest, that if you feel singleton is a way to go, give it a try, but be aware of all the problems you might have to solve before you start the implementation.

Petr
  • 388
  • 5
  • 16
  • @peter I try max avoid singleton pattern for this reason, but this case I don't see other solution. very useful questions, Thx. – Bill Rock Mar 31 '16 at 23:02
-1

YATAS! Yet Another Thread About Singletons. Singletons SHOULD ONLY BE used when they represent something which naturally exists in singular form only for the process you are executing. Like FILESYSTEM, LOG, etc.

At the same time do not avoid singletons if you have real case for them. DO NOT LISTEN to purists, they hardly write any real code besides "code samples".

Riad Baghbanli
  • 2,849
  • 1
  • 9
  • 15