委托(三)(委托与接口的区别)
来源:互联网 发布:小魔女学园 知乎 编辑:程序博客网 时间:2024/05/02 02:27
何时使用委托?何时接口?
在以下情况中使用委托:
1.当使用事件设计模式时.
2.当封装静态方法可取时.
3.当调用方不需要访问实现该方法的对象中的其他属性.方法或接口时.
4.需要方便的组合.
5.当类可能需要方法的多个实现时.
在以下情况使用接口:
1.当存在一组可能被调用的相关方法时
2.当类只需要方法的单个实现时
3当使用接口的类想要该接口强制转化为其他接口或者类类型时
/*皮特的故事*/
using System;
using System.Collections.Generic;
using System.Text;
namespace Delegate
{
interface IWorkEvents
{
void WorkStarted();
void WorkProgressing();
int WorkCompleted();
}
class Worker
{
private IWorkEvents _Events;
public void Advise(IWorkEvents AEvents)
{
_Events = AEvents;
}
public void DoWork()
{
Console.WriteLine("工作:工作开始");
if (_Events != null)
_Events.WorkStarted();
Console.WriteLine("工作:工作进行中");
if (_Events != null)
_Events.WorkProgressing(); ;
Console.WriteLine("工作:工作结束!");
if (_Events != null)
{
Console.WriteLine("工人工作的得分=" + _Events.WorkCompleted());
}
}
}
class Boss : IWorkEvents
{
public void WorkStarted()
{
}
public void WorkProgressing()
{
}
public int WorkCompleted()
{
//因为老板需要处理其他事情
System.Threading.Thread.Sleep(3000);
Console.WriteLine("Better...");
return 4;
}
}
class Universe : IWorkEvents
{
static void WorkStartedWork()
{
Console.WriteLine("Universe notices Worker Starting Work!");
}
static int WorkCompleteWork()
{
//中断处理其他事情
System.Threading.Thread.Sleep(4000);
Console.WriteLine("Universe pleased with Work's Work!");
return 7;
}
public int WorkCompleted()
{
Console.WriteLine("Universe pleased with Work's Work!");
return 7;
}
public void WorkProgressing()
{
}
public void WorkStarted()
{
}
static void Main()
{
Worker wPerter = new Worker();
Boss bBoss = new Boss();
Universe u = new Universe();
wPerter.Advise(bBoss);
wPerter.DoWork();
wPerter.Advise(u);
wPerter.DoWork();
Console.WriteLine("Main:工人工作完成!");
Console.ReadLine();
}
}
}
- 委托(三)(委托与接口的区别)
- 委托,委托与接口的区别
- 委托 与 接口的区别
- 接口和委托的区别
- C#与C++的区别(三) 委托与事件
- 委托与事件的区别
- 委托与事件的区别
- 委托与事件的区别
- 事件与委托的区别
- 委托与事件的区别
- 接口和委托的区别(转)
- 接口和委托的区别在那里?
- 接口,事件与委托
- 接口与委托
- 委托 创建 调用 多播委托 事件 委托与事件的区别
- C#事件与委托的区别
- C#委托与事件的区别
- 委托与事件的联系和区别
- BW简介
- javascript技巧及常用事件方法集合(全)
- 构建基本JSF应用程序(二)
- Windows 驱动:获取当前进程名
- ListCtrl设置字体,颜色,对齐方式
- 委托(三)(委托与接口的区别)
- INFORMIX中对“换行符”的处理
- sql语句性能提高
- PE import function
- 票再难买 过年也要回家
- atmel7s256 的IIC程序
- write process
- 据说是一道百度的笔试题
- windows对象