Delegate Usage : Business Applications

2019-02-10 03:07发布

Background

Given that 'most' developers are Business application developers, the features of our favorite programming languages are used in the context of what we're doing with them.

As a C# / ASP.NET Application developer, I tend to only use delegates when dealing with UI events. In fact (and this is part of my inexperience showing), I don't even know a good context other than events to use delegates in! This is quite scary; but I'm gathering that there are other developers in the same boat.

NB: Answers should pertain to .NET 2.0. .NET 3.0 takes delegates to a different level entirely, and that'll likely be a separate question.

Question:

Besides events, how useful are delegates, and in what Business Application contexts are they most useful?

Update: Jarrod Dixon helpfully linked to the MSDN documentation regarding delegate usage, and I must admit that my favorite Design Patterns Book didn't bring up delegates at all, so I haven't really seen them in use other than for UI events. To expand this question (just a little bit!), What examples can you give for business applications (or really, any application having to deal with a relate-able problem) that would make it easier to digest the MSDN documentation on the subject?

8条回答
在下西门庆
2楼-- · 2019-02-10 03:50

Other than GUI...

  1. event dispatching; some of my business apps are quite complicated, talk to hardware devices, and rely on event queues to keep everything in synch. Delegates are used by these apps for event dispatching.
  2. business rules; some of my business apps have a partial soft-coding ability, where certain events trigger certain rules that are kept in a database. Delegates (in a Dictionary) are used to execute the rules on the client-side. (Plug-ins could be supported, but current are not needed).
  3. general secondary threads (using the SafeThread class, of course!)
查看更多
我命由我不由天
3楼-- · 2019-02-10 03:50

Another great use of delegates is as state machines. If your program logic contains repeated if...then statements to control what state it is in, or if you're using complicated switch blocks, you can easily use them to replicate the State pattern.

enum State {
  Loading,
  Processing,
  Waiting,
  Invalid
}

delegate void StateFunc();

public class StateMachine  {
  StateFunc[] funcs;   // These would be initialized through a constructor or mutator
  State curState;

  public void SwitchState(State state)  {
    curState = state;
  }

  public void RunState()  {
    funcs[curState]();
  }
}

My 2.0 delegate syntax may be rusty, but that's a pretty simple example of a state dispatcher. Also remember that delegates in C# can execute more than one function, allowing you to have a state machine that executes arbitrarily many functions each RunState().

查看更多
登录 后发表回答