質問

I have to implement a flow diagram structure in C#. I will pass in data to the first node, it will check some data item (boolean) then route the data on to one of two subsequent nodes and so on.
The basic logic flow is like this:

  1. node 1

    • If colour red goto node 2
    • else goto node 3
  2. node 2

    • if weight 10 then goto node 4
    • else goto rule 5
  3. node 3

    • if size big then goto node 6
    • else goto node 10

etc

I have been looking at the Chain of Responsibility pattern which initially seemed to solve my problem. However, in most of my nodes (Handlers) I will need to have 2 subsequent nodes (true path and false path) to potentially call.

Looking at implementations of the CoR pattern, it seems that there is a concept of NextHandler (Next Node), but not NextHandlerA and NextHandlerB - for example.

So if not CoR which pattern would be better suited to solve this problem. The rules and the sequence may change frequently.

Thanks for your time.

役に立ちましたか?

解決

The state pattern seems to be a decent fit. You could model each of the nodes in your system as states.

To start with, your Object would be:

public class Object
{
    public string Color { get; set; }
    public int Weight { get; set; }
    public int Size { get; set; }

    private NodeState _state;
    public NodeState State { get { return _state; } set { _state = value; _state.Handle(); } }
}

The business logic of checking color, weight, etc. would sit in the corresponding states. Node1 would look like:

public class Node1 : NodeState
{
    private readonly Object ctx;

    public Node1(Object ctx)
    {
        this.ctx = ctx;
    }

    public void Handle()
    {
        if (ctx.Color.Equals("Red"))
            ctx.State = new Node2(ctx);
        else
            ctx.State = new Node3(ctx);
    }
}

To start with, you'll create the Object and set an initial state to it.

var obj = new Object(){Color = "Red", Weight = 10, Size = 5};
obj.State = new Node1(obj);

Passing the whole object to the Node maybe a smell. Instead, you could even pass in an interface.

The only down-side I see with this approach is some sort of class explosion. There may be as many classes as there are nodes.

However, the design would be quite extensible - in the sense you could add more nodes if required, in line with OCP (Open-closed principle).

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top