In "two ways to implement the observer pattern", the observer pattern has been implemented through the interface, delegate, and event methods. This article uses action to implement this mode.
Let's take a football field as an example. When the referee blew the final whistle, the victory team celebrated and the Failure team fell. Think of the referee as the observer, and the two teams in the game as the observer.
As the observer, the referee must provide an action delegate for the observer method registration.
public class Referee
{
public Action DoSth;
public void ISayGameOver()
{
Console. writeline ("click it... the game is over ~~ ");
DoSth();
}
}
The winning team and the failed team have a common base class.
public class Team
{
private string _name;
public Team(string name)
{
_name = name;
}
public string Name
{
get { return _name; }
}
}
A victory or failure Team, as an observer, must have a method that complies with the action defined in referee.
public class WinTeam : Team
{
public WinTeam(string name) : base(name){}
public void Celebrate()
{
Console. writeline ("We have been promoted, so happy! ");
}
}
public class LoseTeam : Team
{
public LoseTeam(string name) : base(name){}
public void WeAreSad()
{
Console. writeline ("the game is lost, so sad! ");
}
}
The client registers the methods of the failed and victory teams to the action variable, and then triggers the delegate chain and method by a method of the observer.
static void Main(string[] args)
{
Referee referee = new Referee();
VaR winteam = new winteam ("Victory team ");
VaR loseteam = new loseteam ("failed teams ");
// Register the observer
referee.DoSth += winTeam.Celebrate;
referee.DoSth += loseTeam.WeAreSad;
// The event triggered by the observer notifies the observer
referee.ISayGameOver();
}
"Delegation, lambda expressions, and event series" include:
Delegate, Lambda expression, event series 01, Delegate, basic delegate usage, delegate method and Target attribute delegate, Lambda expression, event series 02, when should I use delegate, Lambda expression, event series 03, from delegate to Lamda expression?
Delegation, lambda expressions, event series 04, how the delegation chain is formed, multicast delegation, calling the delegation chain method, delegation chain Exception Handling delegation, lambda expressions, event series 05, action delegate and closure delegate, Lambda expression, event series 06, use action to implement observer Mode
Delegate, Lambda expression, event series 06, use action to implement observer Mode