何时使用委托?何时接口?
在以下情况中使用委托:
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();
}
}
}