定義場景:保存日志功能芬骄,分為:文本形式和數(shù)據(jù)庫形式;
定義日志基類:
///
/// 日志
///
public class LogEntity
{
///
/// 保存
///
public virtual void DoSave() { ?}
///
/// 顯示
///
public virtual void DoShow() { ?}}
擴(kuò)展基類:
///
/// 文本方式日志
///
public class TxtLogEntity : LogEntity
{
public override void DoSave()
{
Console.WriteLine("save to txt");
}
public override void DoShow()
{
Console.WriteLine("show log as txt");
}
}
///
/// 數(shù)據(jù)庫方式日志
///
public class DBLogEntity : LogEntity
{
public override void DoSave()
{
Console.WriteLine("save to db");
}
public override void DoShow()
{
Console.WriteLine("show log as db");
}}
定義日志創(chuàng)建接口:
///
/// 日志創(chuàng)建接口
///
public interface ILogCreator
{
LogEntity CreateLogFactory();}
實(shí)現(xiàn)接口:
public class TxtLogCreator : ILogCreator
{
public LogEntity CreateLogFactory()
{
return new TxtLogEntity();
}
}
public class DBLogCreator : ILogCreator
{
public LogEntity CreateLogFactory()
{
return new DBLogEntity();
}}
利用委托實(shí)現(xiàn)工廠:
///
/// 工廠創(chuàng)建委托
///
///
///
public delegate LogEntity LogEntityCreateFunc(string type);
public static class LogEntityCreateFactory
{
///
/// 創(chuàng)建日志實(shí)體
///
///
///
///
public static LogEntity CreateEntity(string aType, LogEntityCreateFunc createFunc)
{
return createFunc(aType);
}}
客戶端調(diào)用:
static void Main(string[] args)
{
LogEntity log = LogEntityCreateFactory.CreateEntity("txt", MyCreateFunc);
log.DoSave();
log.DoShow();
Console.ReadKey();
}
///
/// 自定義工廠創(chuàng)建方式
///
///
///
static LogEntity MyCreateFunc(string aType)
{
if (aType == "txt")
{
return (new TxtLogCreator()).CreateLogFactory();
}
else if (aType == "db")
{
return (new DBLogCreator()).CreateLogFactory();
}
else
{
return null;
}}
優(yōu)點(diǎn):
1.充分體現(xiàn)了依賴倒置原則,?日志創(chuàng)建接口的設(shè)計泵额,保證了最大的可擴(kuò)展度,即如果日后需要實(shí)現(xiàn)一個基于第三方的日志功能,只需要實(shí)現(xiàn)接口即可庵芭,不需要修改原代碼;
2.利用委托的特性雀监,可以自定義創(chuàng)建規(guī)則双吆,采用十分靈活的注入方式,最大化的解除了業(yè)務(wù)邏輯和代碼的耦合会前。