Can I make a “global” object to store variables fo

2019-07-22 12:15发布

问题:

I am creating a graphing application that will display several graphs. The graphs will need access to some global data and some graph-specific data. For example, I want the colors consistent, so that would be global, but the specific graphs can have different grid spacing (per graph).

I created a "master object" with set defaults and a derived object with per graph configuration options

class GraphMasterObject {
  public Color gridcolor = Color.Red;
}

class GraphObject : GraphMasterObject {
  public int gridSpacing = 10;
}

Now, from my understanding, I should be able to do this

GraphObject go = new GraphObject();
Color c = go.gridColor;

How can I make it so that if I change go.gridColor, it will change across all objects that inherit from GraphMasterObject? Is this even possible? If not, what other solutions are possible? Something like

GraphMasterObject gmo = new GraphMasterObject();
gmo.gridColor = Color.Blue;

or

GraphObject go = new GraphObject();
go.gridColor = Color.Blue;

回答1:

One common approach to have a single object instance shared among many objects is the Singleton Pattern.

http://en.wikipedia.org/wiki/Singleton_pattern

With the Singleton Pattern, any object can request the singleton object and will be returned the same singleton object instance as any other object that requests the singleton object.

That seems like a fine solution in your situation.

One way in C# to implement this pattern is by using a static property, e.g.:

public class MySingleton
{
    static private MySingleton singleton = null;

    private static readonly object padlock = new object();

    static public MySingleton Retrieve
    {
        get
        {
            lock (padlock)
            {
                if (singleton == null) singleton = new MySingleton(); // Initialize as needed
            }
            return singleton;
        }
    }
}

Usage

MySingleton singleton = MySingleton.Retrieve;

UPDATE

Here's an implementation that is superior to the one above, from the article provided by @Marksl

public sealed class Singleton
{
    private static readonly Lazy<Singleton> lazy =
        new Lazy<Singleton>(() => new Singleton());

    public static Singleton Instance { get { return lazy.Value; } }

    private Singleton()
    {
    }
}


回答2:

Why use inheritance at all? Why not just have a GlobalGraphSettings object which you pass to all of your Graph objects, then you can just do

MyColor = Graph.GlobalSettings.Color;