Question

I'm building an inventory of items as a class called MyLib, the library initialization takes quite some time and needs to be done only once. After that an instance of any item in the inventory can be created at will using the relevant item class, however item instantiation shouldn't be allowed unless the library is instantiated. The only way I found this to be possible is by nesting the item class inside the library class as shown below, but I'm wondering if there's a better way of doing this.

public class MyLib 
{
    protected string LibFilePath;

    public MyLib ()
    {
        /* Time-consuming Library initialization code here
           needs to be done only once

         LibFilePath initialized
         etc.

         */
    }

    public class LibItem1
    {
        /* Must ensure that MyLib is initialized
         * Must have access to Library information like LibFilePath, etc.
         */
    }
}
Was it helpful?

Solution

You can force this also like this:

public class MyLib 
{
    public static void InitializeMyLib(...)
    {
        if (instance != null)
        {
            throw new InvalidOperationException("Already initialized");
        }

        instance = new MyLib(...);
    }

    public static MyLib GetInstance()
    {
        if (instance == null)
        {
            throw new InvalidOperationException("Not initialized");
        }

        return instance;
    }

    private MyLib(...)
    {
        ...
    }

    private static MyLib instance;
}

public class LibItem1
{
    public LibItem1()
    {
        MyLib.GetInstance(); // will throw if doesn't exist
    }
}

If having a singleton is OK here - your description of this class's behaviour suits this pattern. Of course generic exceptions are used for simplicity, and you can use ordinary create-on-first-use-pattern instead of InitializeMyLib and GetInstance separate methods. However, I'm guessing that this is not the case, as then you wouldn't have to prohibit creating Libitem1's before the initialization.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top