Design Question WRT controlling access to private methods

J

John B

I have a situation where I need to control the creation of a class.
I need to be able to create it externally but only by classes that I define.
To accomplish this I thought of the following process:

Define a delegate that returns an instance of my class.
Pass this an instance of this delegate to any classes that I want to be
able to create instances of myclass.

i.e.

//Safe class
using System;
using System.Collections.Generic;
using System.Text;

namespace DelegateCreation
{
public class MySafeClass
{
public delegate MySafeClass CreateMySaveClassDelegate();

private MySafeClass()
{
}

private static MySafeClass Create()
{
return new MySafeClass();
}

public static void Load()
{
List<MySafeClass> instances =
ClassCreator.CreateMySafeClass(new CreateMySaveClassDelegate(Create));
}
}
}

//Class creator
using System;
using System.Collections.Generic;

namespace DelegateCreation
{
public class ClassCreator
{

public static List<MySafeClass>
CreateMySafeClass(MySafeClass.CreateMySaveClassDelegate myDelegate)
{
List<MySafeClass> returnList = new List<MySafeClass>();
returnList.Add(myDelegate.Invoke());
return returnList;
}
}
}
 
M

Mattias Sjögren

John,
I have a situation where I need to control the creation of a class.
I need to be able to create it externally but only by classes that I define.
To accomplish this I thought of the following process:

Define a delegate that returns an instance of my class.
Pass this an instance of this delegate to any classes that I want to be
able to create instances of myclass.

And your question is what exactly?

The code you posted doesn't seem to fulfill your "only by classes that
I define" requirement. A delegate doesn't add any "security", just a
level of indirection.


Mattias
 
J

John B

Mattias said:
John,


And your question is what exactly?

The code you posted doesn't seem to fulfill your "only by classes that
I define" requirement. A delegate doesn't add any "security", just a
level of indirection.


Mattias
Yes it does, because I (MySafeClass) am the only one that can create
this delegate pointing to my (private) Create method.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top