Object oriented design help from C ++ to C #
Hey, I usually run into a situation where I create a class that should only be created by one or more classes. In this case, I would make my constructor private and make it a friend class for objects that need to be able to create it. For example (in C ++):
class CFoo
{
friend class CFoo;
// private ctor because only a select few classes should instantiate
private:
CFoo()
{
... Do stuff
}
}
class CBar
{
// CBar is one of the few classes that only need to use CFoo
CFoo *m_pFoo;
CBar()
{
m_pFoo = new CFoo;
}
}
So my question is, is this stupid? Or is there a better way to achieve this? I'm particularly interested in the way it would work with C #, given that the language is missing the friend keyword. Thank.
source to share
The goal here is that you cannot have a CFoo until you have a working CBar.
You can achieve the same thing with C # by having a private constructor for CFoo and then creating a static method in CFoo that takes a CBar argument and calls the specified constructor and returns a new CFoo.
It will be something like the System.Drawing.Graphics.FromImage (Image) method.
The question of why C # doesn't have the friend keyword has been covered elsewhere .
source to share
Just because only a few specific classes use CFoo doesn't mean that you should explicitly prevent others from using it. If you really need to, you can rethink your design. You definitely don't want to force this high number of links within your code. Try to explain in detail why you are doing this, so we can suggest a good solution?
source to share
To think if this is stupid or not, could you please give a more specific example of what classes are?
I would say that using a friend for no good reason sounds a little strange to me ... in C # you have such a thing as an assembly, so instead you can use an internal constructor or a private constructor and several static creation methods with different access ( protected, public, internal ...)
source to share
First, the friend's declaration is in the wrong class. CFoo needs a friend CBar to give CBAR access to private members.
Secondly, yes, generally it should be avoided. Classes don't have to care about how / where they are used. If they do, then this functionality should probably be broken down in different ways.
source to share
Just make the class private. This just limits the scope of your DLL (exe, etc.). There's nothing cool like declaring a friend in C #, but Marcin is right that you should revisit projects like this. If you really need the support of a "friend", you can use reflection to simulate it at runtime.
source to share