Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object Oriented Paradigm - C# [duplicate]

Tags:

c#

oop

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#?

like image 644
Muthu Ganapathy Nathan Avatar asked Nov 28 '22 08:11

Muthu Ganapathy Nathan


1 Answers

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); 
like image 51
Tigran Avatar answered Dec 12 '22 09:12

Tigran