event demo:
using System;
namespace EventDemoConsoleApplication
{
class Program
{
static void Main(string[] args)
{
Orange orange=new Orange();
Apple apple=new Apple();
Sail sail =new Sail();
Eat eat=new Eat();
FruitTranser fruitTransfer = new FruitTranser();
fruitTransfer.FruitTransferEvent += new FruitTranser.FruitEventHandler(sail.Deal);
fruitTransfer.FruitTransferEvent += new FruitTranser.FruitEventHandler(eat.Deal);
fruitTransfer.SetFruitEventArgsArrivingFruit(orange);
Console.WriteLine();
fruitTransfer.SetFruitEventArgsArrivingFruit(apple);
Console.WriteLine();
fruitTransfer.FruitTransferEvent -= new FruitTranser.FruitEventHandler(sail.Deal);
fruitTransfer.SetFruitEventArgsArrivingFruit(apple);
Console.ReadKey();
}
}
abstract public class Fruit
{
public string FruitName { get; protected set; }
}
class Apple:Fruit
{
public Apple()
{
this.FruitName="Apple";
}
}
class Orange:Fruit
{
public Orange()
{
this.FruitName="Orange";
}
}
public class FruitTranser
{
public int InstancCount { get; private set; }
public class FruitEventArgs : EventArgs
{
public Fruit thisFruit { get; private set; }
public FruitEventArgs(Fruit fruit)
{
thisFruit = fruit;
}
}
public delegate void FruitEventHandler(Object sender, FruitEventArgs args);
public event FruitEventHandler FruitTransferEvent;
protected virtual void OnFruitTransferEvent(FruitEventArgs e)
{
if (FruitTransferEvent != null)
{
this.InstancCount++;
FruitTransferEvent(this, e);
}
}
public void SetFruitEventArgsArrivingFruit(Fruit fruit)
{
FruitEventArgs e = new FruitEventArgs(fruit);
OnFruitTransferEvent(e);
}
}
abstract class FruitFactory
{
public void Deal(Object sender,FruitTranser.FruitEventArgs e)
{
Console.WriteLine("Event counter:{1}", ((FruitTranser)sender).GetType(), ((FruitTranser)sender).InstancCount);
DealFruit(e.thisFruit);
}
protected abstract void DealFruit(Fruit fruit);
}
class Sail : FruitFactory
{
protected override void DealFruit(Fruit fruit)
{
Console.WriteLine("Sail Fruit: {0}", fruit.FruitName);
}
}
class Eat : FruitFactory
{
protected override void DealFruit(Fruit fruit)
{
Console.WriteLine("Eat Fruit: {0}", fruit.FruitName);
}
}
}