Search code examples
c#.netoopencapsulation

How to pass the field to list of child objects in "has a" relationship


I have a class Step

public class TrainingStep
{
    private List<Part> parts;
    public Part currentPart;
   
    public void AddPart(Part part)
    {
       parts.Add(part);
    }

    ///a lot of public methods which are called from one layer above Step( a class containing Step list)
}

In this code the Part doesn't know anything about Step.

The currentPart is changing very often and I want all of parts to know which is the current now

To achieve this I considered to add step as a parameter for Part class constructor, in order every part knows to which Step it belongs. Something like this

public Part(Step step, ...)
{
  this.step = step;
}

But the problem of such kind of solution is that I can access every public method in Step class from Part using the reference which I've passed via constructor.

But I want to access only currentPart field from Part. How can I achieve this?


Solution

  • You might define a Func<Part> which returns your currentPart and pass this delegate to your parts.

    public class TrainingStep
    {
        private List<Part> parts;
        public Part currentPart;
        private Func<Part> getCurrentPartFunc = () => currentPart;
       
        public void AddPart(Part part)
        {
           part.GetCurrentpart = getCurrentPartFunc;
           parts.Add(part);
        }
    }
    
    class Part
    {
        public Func<Part> GetCurrentPart {get; set;}
    }