My Scenario :
Consider two classes class SubGroup
, and class Group
.
I want no other classes to create SubGroup's
object without a Group
,
because SubGroups
will not exist without Group
.
But,
Group
can exist without any SubGroup
.
Also, Group
can contains multiple SubGroup's
.
class SubGroup{
private SubGroup(int arg){
}
}
class Group{
List<SubGroup> list;
Group(int param){
list = new List<SubGroup>();
}
SubGroup createChild(int args){
return new SubGroup(int args); // I need to access SubGroups constructor?? (without using inheritance).
}
}
class C{
Group b = new Group(param);
SubGroup a = b.createChild(args); // since constructor is not visible here. bcz, SubGroup will not exist without Group.
}
What I have tried :
I could make Group to inherit from SubGroup and make SubGroup constructor as protected, but that says is-a
releationship, that is every Group is a SubGroup. But actually it is not.
Moreover I want an arg to create a subGroup, but I have no argument for subgroup during the creation of Group, hence I cannot use inheritance.
Inner Classes : Inner classes will not help because I have SuperGroup,SubGroup,MicroGroup
many layers.
Actually it is an financial project there, I have Account,AccountHead,SubGroup,Group
etc.. so too may inner layers will be created. which will reduce the readability.
How could I achieve in C#?
I want no other classes to create SubGroup's object other than Group, because SubGroups will not exist without Group.
Why not just inverse a dependency in declaration:
class Group{
List<SubGroup> list;
...
public void AddSubgroup(SubGroup sub) {
list.Add(sub);
}
}
class SubGroup{
///private ctor, can be used only inside class
private SubGroup(int arg){
}
public static Subgroup Create(Group parent, int arg) {
Subgroup sub = new Subgroup(arg);//use private ctor
parent.AddSubgroup(sub);
return sub;
}
}
So all this you will use like:
var group = new Group();
var subgroup = Subgroup.Create(group, 2);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With