G
G
Georgy Pelageykin2016-11-14 16:51:35
Mono
Georgy Pelageykin, 2016-11-14 16:51:35

How is it more convenient to aggregate events that notify about property changes?

For example, let there be a ship. It is made up of compartments. Any equipment can be installed in the compartments. A ship has a mass that is made up of the mass of all its compartments. The mass of each compartment, for example, depends on whether equipment is installed in it or not. And the mass of the equipment itself can also vary, for example, depending on the mass of fuel in the fuel tank. And now, each component from this chain must notify about a change in its mass.
For clarity, the spherical class hierarchy:

public class Spacecraft
{
  public IEnumerable<Hardpoint> Hardpoints { get; private set; }

  public Single Mass => Hardpoints.Select(hp => hp.Mass).Sum();
}

public class Hardpoint
{
  public Equipment InstalledEquipment { get; private set; }

  public Boolean IsEquipmentInstalled => InstalledEquipment != null;

  public Single Mass => IsEquipmentInstalled ? InstalledEquipment.Mass : 0;
}

public abstract class Equipment
{
  public event Action MassChanged;

  public Single Mass
  {
    get { return _mass; }
    protected set
    {
      _mass = value;
      MassChanged?.Invoke();
    }
  }

  private Single _mass;
}

(nowhere more spherical)
In other words, there is a tree of properties (in this case, Mass), each of which depends on its descendants, and the property at any of the levels must be able to notify about its change (i.e. the issue in the implementation of MassChanged in Hardpoint and Spacecraft is the least costly way). Of course, I can simply make a MassChanged event in Hardpoint and call it on a similar event from the installed equipment or when it is changed. Also in Spacecraft. A lot of the same code of subscriptions / unsubscribes, error-prone.
Another option is to break the encapsulation and make the event invocator in Hardpoint public by calling it when calling the mass setter along with calling your event. Do the same with Spacecraft. A little less code, but messy.
Are there any more advanced practices?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
MrDywar Pichugin, 2016-11-14
@Dywar

The ship at each moment of time has a certain state.
Something can change it, and someone must subscribe to these changes.
Flux -> Redux , you can borrow the implementation.
Implementing Redux in C#
Or the standard INotifyPropertyChanged interface.

R
Roman, 2016-11-15
@yarosroman

You might like reactivex.io

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question