日期:2014-05-16 浏览次数:20681 次
委托的实例:
class Program { static void Main(string[] args) { Teacher Tc = new Teacher("赵老师"); //实例化老师和学生 Student St1 = new Student("张三"); Student St2 = new Student("李四"); //把学生的行为交给 委托 Tc.TeacherCome += new Teacher.EventHandler(St1.StopCopyWork); Tc.TeacherCome += new Teacher.EventHandler(St2.StopWhisper); Tc.Come(); } } class Teacher { private string name; public Teacher(string name) { this.name = name; } public delegate void EventHandler(); //声明一个委托EventHandler public event EventHandler TeacherCome; //声明事件名称,事件类型为EventHandler public void Come() //老师的行为 { Console.WriteLine("{0}来了", name); if (TeacherCome != null) //如果需要委托,则执行下面程序 { TeacherCome(); } } } class Student { private string name; public Student(string name) { this.name = name; } public void StopWhisper() { Console.WriteLine("老师来了,{0}停止说话",name); } public void StopCopyWork() { Console.WriteLine("老师来了,{0}停止抄作业",name); } }
运行结果:
代理模式:
为其他对象提供一种代理,来帮助达到目的。
代理模式实例:
class Program { static void Main(string[] args) { SchoolGirl mm = new SchoolGirl(); mm.Name = "jiaojiao"; Proxy daili = new Proxy(mm); daili.GiveDolls(); daili.GiveFlowers(); daili.GiveChocolate(); } } class SchoolGirl //定义 女孩类 { private string name; public string Name { get { return name; } set { name = value; } } } interface IGiveGift //创建一个送礼物的接口 { void GiveDolls(); void GiveFlowers(); void GiveChocolate(); } class Pursuit:IGiveGift //追求者类,使用送礼物的接口 { SchoolGirl mm; //要追求女孩的名字 public Pursuit(SchoolGirl mm) { this.mm = mm; } public void GiveDolls() { Console.WriteLine(mm.Name+"送你洋娃娃"