lundi 4 mars 2019

How do I ensure a single instance without singleton

I am building an application that scans my file system doing all kinds of checks. I put all the logic for this in a class "PScannerCore" (in its own namespace) so that it's seperate from my GUI (now Windows Forms).

Before I run the scan, I need to pass in some settings, like which folder and extensions to scan.

After the scan I display the results which were stored by the scan logic in various collection type class members.

This is all done by the following, which is executed when I click the "Scan" button in my UI:

PScannerCore.PScannerCore pScan = new PScannerCore.PScannerCore(Settings.Default.Folders.ToDictionary(),
                                                                            this.Extensions,
                                                                            Settings.Default.Categories.Cast<string>().ToList(),
                                                                            Settings.Default.SplitTokens.Cast<string>().ToList(),
                                                                            Settings.Default.IgnoreList.Cast<string>().ToList());

ClearResults();

await Task.Run(() => pScan.Scan());

AddResultsToCategoriesGrid(pScan.Categories);
AddResultsToListView(pScan.Issues);

Problem here is that every time I click the scan button, a new instance of "PScannerCore" is created, which looks like a bad idea. I don't need to save anything from the previous scan so I'd like to just re-use the same object.

I do need to pass in new settings before a next run because they might have changed (different folders to scan). The results from the previous run (Categories, Issues), will need to be replaced with those of the new run.

So because this class stores data it can't be a static class.

I know about the Singleton design pattern but I also read that it's actually an anti-pattern and shouldn't be used. But I suspect that in my specific case it isn't even needed.

So what should I ideally do here to prevent a new object from being created each time? Simply just move the initialization to the load event of my application and set the settings trough properties?

This would work but still I feel like there must be a better way. Also if I do it this way, I don't enforce that only one instance can be created.

Aucun commentaire:

Enregistrer un commentaire