Y.S
Y.S

Reputation: 1862

design pattern like electricity switch?

I'm coding in c# and currently implementing an "electricity switch" like component.

General idea is there are a bunch of classes implementing a ISwitch interface, and when one is false it basically triggers an Off() action and when all are true then On().

Idea is pretty clear and I'm pretty sure there is a design pattern for such behavior / functionality, would appreciate a reference to documentation so I can educate myself and look at best practices,

cheers

Upvotes: 0

Views: 103

Answers (1)

Scott Hannen
Scott Hannen

Reputation: 29222

Here's an example:

public delegate void HandleSwitchStateChanged(ISwitch source, bool switchedOn);

public interface ISwitch
{
    event HandleSwitchStateChanged SwitchStateChanged;
    bool SwitchedOn { get; }
}

public enum SwitchesState
{
    AllOn,
    AllOff,
    Mixed
}

public class MonitorsMultipleSwitches
{
    private readonly ISwitch[] _switches;
    private SwitchesState _switchesState;

    public MonitorsMultipleSwitches(ISwitch[] switches)
    {
        _switches = switches;

        foreach (var item in switches)
        {
            item.SwitchStateChanged += HandleSwitchStateChanged;
        }
    }

    public void HandleSwitchStateChanged(ISwitch source, bool switchedOn)
    {
        SwitchesState newState;
        if (_switches.All(s => s.SwitchedOn))
            newState = SwitchesState.AllOn;
        else if (_switches.All(s => !s.SwitchedOn))
            newState = SwitchesState.AllOff;
        else
            newState = SwitchesState.Mixed;

        if (newState == _switchesState) return; // no meaningful change
        _switchesState = newState;

        // do something.
    }
}

In this example one class is monitoring multiple switches. If the state of any of them changes it checks to see if all are on, all are off, or some are on and some are off. Then, if that's different from the state it was previously in, it can react as needed.

(Perhaps AllOff isn't a state you care about - either they're all on or you don't care.)

Upvotes: 2

Related Questions