Domanda

With this code:

public class MyClass
{
    public int Number;

    private static MyClass myClass;

    ...

    public MyClass GetInstance()
    {
        ...

        return myClass;
    }
}

Is there a way I can support both of the following statements?

MyClass.Number = 5;

where MyClass retrieves the static class for storing the value of Number

and

MyClass myLocalClass = new MyClass();

or an alternative that gets away from the Singleton design pattern since I would like to be able to create an instance as well.

Thanks for looking!

È stato utile?

Soluzione

What you are looking for, is the MonoState pattern. I'll quote Agile Principles, Patterns, and Practices in C# from Robert C. Martin

The MONOSTATE pattern is another way to achieve singularity. It works through a completely different mechanism.

The first test function simply describes an object whose x variable can be set and retrieved. But the second test case shows that two instances of the same class behave as though they were one. If you set the x variable on one instance to a particular value, you can retrieve that value by getting the x variable of a different instance. It's as hough the two instances are simply different names for the same object.

So you can instantiate 2 or more classes, but they'll all share the same values.

Here's an example of the implementation :

public class Monostate
{
    private static int itsX;

    public int X
    {
        get { return itsX; }
        set { itsX = value; }
    }
}

And the tests, so you can see how it is used :

using NUnit.Framework;

[TestFixture]
public class TestMonostate
{
    [Test]
    public void TestInstance()
    {
        Monostate m = new Monostate();
        for (int x = 0; x < 10; x++)
        {
            m.X = x;
            Assert.AreEqual(x, m.X);
        }
    }
    [Test]
    public void TestInstancesBehaveAsOne()
    {
        Monostate m1 = new Monostate();
        Monostate m2 = new Monostate();
        for (int x = 0; x < 10; x++)
        {
            m1.X = x;
            Assert.AreEqual(x, m2.X);
        }
    }
}

Altri suggerimenti

What you want is simply a static member. By definition a Singleton has only one instance which means you cannot explicitly instantiate it.

Your class should simply be.

public class MyClass
{
    public static int Number;
}

However unless you also have some non-static members, creating multiple instances of the class is pointless.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top