抽象类负责对类的抽象,经常使用在Template等模式中
接口负责对类的行为的抽象
事件负责对两个对象的通信,而不需要建立两个对象直接联系,避免了对象的间的耦合
Action与Func在基于策略模式实现弱依赖关系,即Test(IStrategy strategy);实现对抽象方法取代真实方法的调用。
抽象类实现
public abstract class Test
{
public virtual int Add(int x,int y)
{
return x + y;
}
public abstract int Muliti(int x, int y);
}
接口实现
public interface IOperation
{
void Logger(string message);
}
public abstract class Test:IOperation
{
public virtual int Add(int x,int y)
{
return x + y;
}
public abstract int Muliti(int x, int y);
public void Logger(string message)
{
throw new NotImplementedException();
}
}
事件实现
public interface IOperation
{
void Logger(string message);
}
public abstract class Test:IOperation
{
public event Action OnRefresh;
public virtual int Add(int x,int y)
{
if (OnRefresh != null)
{
Action action = OnRefresh;
action();
}
return x + y;
}
public abstract int Muliti(int x, int y);
public void Logger(string message)
{
throw new NotImplementedException();
}
}
Action与Func实现对常见异常代码的封装和调用
class _09exception
{
public static void Main1()
{
BussinessHelper.Action(() =>
{
throw new MyException("aa", "bb");
});
}
}
class BussinessHelper
{
public static void Action(Action action)
{
try
{
if (action != null)
action();
}
catch (MyException ex)
{
}
}
}
class MyException : Exception
{
public MyException(string message)
: base(message)
{
}
public MyException(string message, string title)
:base(message)
{
Console.WriteLine(message);
}
}