开发者

C# Limit creation of class instance to within namespace

I have two objects, RoomManager and Room, there will be several Rooms and one RoomManager. I want the RoomManager to be the only one allowed to create a Room object. So I'm wondering if there is a way to make the Room constructor (and the re开发者_运维知识库st of the Room methods/properties) only accessible to the RoomManager. I was thinking maybe moving them to their own namespace and making Room private or internal or something. From Accessibility Levels (C# Reference) I see that internal is for the entire assembly though, not just the namespace.


No, C# (and .NET in general) has no access modifiers which are specific to namespaces.

One fairly hack solution would be to make Room just have a private constructor, and make RoomManager a nested class (possibly just called Manager):

public class Room
{
    private Room() {}

    public class Manager
    {
        public Room CreateRoom()
        {
            return new Room(); // And do other stuff, presumably
        }
    }
}

Use it like this:

Room.Manager manager = new Room.Manager();
Room room = manager.CreateRoom();

As I say, that's a bit hacky though. You could put Room and RoomManager in their own assembly, of course.


You can do something like this:

var room = Room.Factory.Create();

If the constructor of Room is private, it will still be accessible from Room.Factory if you declare the factory class inside the Room class.


Defining the Room inside of RoomManager itself and making it's constructor private could be helpful.

EDIT : But the best solution I think is that to extract an abstract class of the Room, and expose that class to clients.

No one can create an instance of the abstract class.


You should implement 'Singleton pattern'. It creates object only once and any subsequent attemps to create object of that type will actually returns already created object.
You should create class factory which would implement singleton for RoomManager. Room, in turn, should be private type of RoomNamager. RoomNamager manager should have method for Room creation. But in this case you cannot access Room properties outside of RoomManager class. To solve this problem I recomend you to create IRoom public interface which would grant access to room functionality. So your create room method would return IRoom interface.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜