开发者

Access Modifier / Design - What to do/use for this scenario of class accessibility

I've recently implemented a singleton class, and within it I've declared a static generic list of (T) class. Anyway this is my first attempt at using singleton but everything I've tried work so far.

My Question: To be consistent, I don't want the MasterSiteData to be visible to other classes except my Singleton class. I thought of maybe encapsulating both classes within a parent class which would give me new options. However I'd rather have some of the great opinions you all provide :).

 public sealed class Singleton
    {
        private static readonly Singleton Instance = new Singleton();

        private Singleton()
        {
        }

        public static List<MasterSiteData> MasterDetails = new List<MasterSiteData>();
    }

    public class MasterSiteData
    {
        public Guid GuidId { get; set; }
        public string Uri { get; set; }
        public int LinkNumber { get; set; }

        public MasterSiteData(Guid guid, string uri, int linknumber)
        {
            GuidId = guid;
            Uri = uri;
            LinkNumber = linknumber;
        }
    }

EDIT:

C开发者_Python百科rap! I totally forgot that I need to instantiate the MasterSiteData class to add a record to my list, therefore I really can't have it hidden, for example

 Singleton.MasterDetails.Add(new MasterSiteData(Guid.NewGuid(), "lol1", 1337));


Use an interface and make the implementation private to Singleton. (Also, don't use public fields, use properties):

public sealed class Singleton
{
    public static List<ISiteData> Details { get; private set; }

    private Singleton()
    {
        //create new instances of MasterSiteData and add to the list
    }

    private class MasterSiteData : ISiteData
    {
        public Guid GuidID {get;set;}
        public string Uri {get;set;}
        public int LinkNumber {get;set;}

        public MasterSiteData(Guid guid, string uri, int linkNumber)
        {
            GuidID = guid;
            Uri = uri;
            LinkNumber = linkNumber;
        }
    }
}

public interface ISiteData
{
    Guid GuidID {get;set;}
    string Uri {get;set;}
    int LinkNumber {get;set;}
}


In order to achieve the accessibility level you require, you will have to declare your MasterSiteData class inside the Singleton class, and mark it's accessibility level as private.

For example:

 public class Singleton
    {
        private MasterSiteData innerClass = new MasterSiteData();

        private class MasterSiteData
        {
            // your mastersitedata class
        }
    }

Since the Singleton class effectively "owns" the MasterSiteData class, it can create instances of the MasterSiteData class itself, however no code outside of the outer Singleton class can access or create instances of the MasterSiteData type.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜