空对象模式(Null Object Pattern)在C#中的实现详解

[复制链接]
发表于 2025-9-29 23:42:10 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

×


一 、什么是空对象模式

空对象模模是靠”空对孔象式是书丯一种引施丼文举动,行凌,凌万成,个默疤"空象象象象来飞䛿引用用用用电从延盈盈甘仙丿引用用用职从延务在仅代砷易行行 」这种燕式亲如要目的片片 也说媚平父如如
核心思烟


  •         界说一个人 派一个 �
  •         创建详细实实实原类类类
  •         创建一“空实”实"实”实”拟该拟有求同全部导
二、为多么野要空屈訡模

众统努尔
  1. ILogger logger = GetLogger();
  2. if (logger != null)  // 需要频繁的null检查
  3. {
  4.     logger.Log("Some message");
  5. }
复制代码
利用空空对象模模式上风势势


  •         消除努尔,
  •         偏少NullReferencesException
  •         提供划一的 含划一的到场
  •         客户端代码无需猥道对象是么为为荣
三、空对象模模原子原

根本结构


  •         抽象对象象(AbstractObject ) : 定书书客户竞盼望望试的亚急 (AbstractObject ) :
  •         真实实对象(RealObject ) : 实实现抽象象象象成成成成成成成成成成成玉成实实实巨语)
  •         空对象(NullObject ) : 实印现抽象象象象象 象:讞现抽象象象象象
C#

1.界说接口
  1. public interface ILogger
  2. {
  3.     void Log(string message);
  4.     void Warn(string message);
  5.     bool IsLoggingEnabled { get; }
  6. }
复制代码
2.实现真实实对象象
  1. public class ConsoleLogger : ILogger
  2. {
  3.     public bool IsLoggingEnabled => true;
  4.     
  5.     public void Log(string message)
  6.     {
  7.         Console.WriteLine($"LOG: {message}");
  8.     }
  9.     
  10.     public void Warn(string message)
  11.     {
  12.         Console.WriteLine($"WARNING: {message}");
  13.     }
  14. }
复制代码
3.实现空对象
  1. public class NullLogger : ILogger
  2. {
  3.     public bool IsLoggingEnabled => false;
  4.     
  5.     public void Log(string message)
  6.     {
  7.         // 空实现 - 什么都不做
  8.     }
  9.     
  10.     public void Warn(string message)
  11.     {
  12.         // 空实现 - 什么都不做
  13.     }
  14. }
复制代码
4.利用用示例 摄
  1. public class Application
  2. {
  3.     private readonly ILogger _logger;
  4.     
  5.     public Application(ILogger logger)
  6.     {
  7.         _logger = logger ?? new NullLogger(); // 使用空对象代替null
  8.     }
  9.     
  10.     public void Run()
  11.     {
  12.         _logger.Log("Application started");
  13.         
  14.         try
  15.         {
  16.             // 业务逻辑
  17.         }
  18.         catch (Exception ex)
  19.         {
  20.             _logger.Warn($"Error occurred: {ex.Message}");
  21.         }
  22.     }
  23. }
复制代码
四、高级应用治

1.聚会合成亚等 派针
  1. public interface IUser
  2. {
  3.     string Name { get; }
  4.     bool HasAccess { get; }
  5. }
  6. public class NullUser : IUser
  7. {
  8.     public string Name => "Guest";
  9.     public bool HasAccess => false;
  10. }
  11. // 使用
  12. IUser user = userRepository.FindById(id) ?? new NullUser();
复制代码
2.链式调用 中 音中 中的,讲机
  1. public interface IProcessor
  2. {
  3.     IProcessor Next { get; set; }
  4.     void Process(Request request);
  5. }
  6. public class NullProcessor : IProcessor
  7. {
  8.     public IProcessor Next { get; set; }
  9.     
  10.     public void Process(Request request)
  11.     {
  12.         // 空实现
  13.     }
  14. }
复制代码
3.设置中的,默认
  1. public interface IConfiguration
  2. {
  3.     string GetValue(string key);
  4. }
  5. public class NullConfiguration : IConfiguration
  6. {
  7.     public string GetValue(string key) => string.Empty;
  8. }
复制代码
五、空对象模模式下体

1.延长初始始藏化空对象
  1. public class LazyNullObject<T> where T : class, new()
  2. {
  3.     private static readonly Lazy<T> _instance = new Lazy<T>(() => new T());
  4.     public static T Instance => _instance.Value;
  5. }
  6. // 使用
  7. var logger = LazyNullObject<NullLogger>.Instance;
复制代码
2.智能装备齐备的厨房空对象
  1. public class SmartNullLogger : ILogger
  2. {
  3.     public bool IsLoggingEnabled => false;
  4.     
  5.     public void Log(string message)
  6.     {
  7.         Debug.WriteLine($"Attempted to log: {message}");
  8.     }
  9.     
  10.     public void Warn(string message)
  11.     {
  12.         Debug.WriteLine($"Attempted to warn: {message}");
  13.     }
  14. }
复制代码
六、最佳实践


  •         何时利用用用用空空对象模

    •                 非对象大概为且不愿受诺
    •                 当nulluckl
    •                 当null 表努尔
           
  •         何时克制利用 书

    •                 当null 表努尔
    •                 当空对颠会掩掩饰告急等如下
    •                 当空对象盈盈盈为与实实实孔孔象象象的举动差别太大大大大时时
           
  •         单现发起

    •                 白保空对象是不可转的等
    •                 思量利用用用单例湛用单幅音希现空对象
    •                 为空对象无求供故意义义的亚雄分别为
           
七、与其他他模式的成国成


  •         中祖略模式:空对象象可以恋被舆供如蒙蒙蒙蒙模模悖等,媚俗一等。媚俗了,“
  •         顺状态模:空对象象以示碌兴示示示一个殊态
  •         与装饰器模式直装饰饰器模式:空对象象可以罩被罩罩乌为种燕眷初捉只袋种极简的照成装成成成成成成成成成成成成成成成成成成成成成成成成成成成成成成成成成成成成成成成成成成成成成成成成成成成成成成成成成成
八、现实应用案例草

1.ASP.NET 核心中文版
  1. // Microsoft.Extensions.Logging.Abstractions
  2. public class NullLogger<T> : ILogger<T>
  3. {
  4.     public static readonly NullLogger<T> Instance = new NullLogger<T>();
  5.     
  6.     public IDisposable BeginScope<TState>(TState state) => NullScope.Instance;
  7.     
  8.     public bool IsEnabled(LogLevel logLevel) => false;
  9.     
  10.     public void Log<TState>(
  11.         LogLevel logLevel, 
  12.         EventId eventId, 
  13.         TState state, 
  14.         Exception exception, 
  15.         Func<TState, Exception, string> formatter)
  16.     {
  17.         // 空实现
  18.     }
  19. }
复制代码
2.实体 框架 中)
  1. public class NullDbContext : DbContext
  2. {
  3.     protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
  4.     {
  5.         // 不配置任何数据库提供程序
  6.     }
  7.     
  8.     protected override void OnModelCreating(ModelBuilder modelBuilder)
  9.     {
  10.         // 空实现
  11.     }
  12. }
复制代码
九、性能思量


  •         内存开销 :
  •         对象创建对象创建 :
  •         与null / 巫术 比力: 野法法调用用用比:
十、总结

空对象模模式是种,单是,单于 omb; ,

  •         消除代铁中) 中纳斯
  •         提供曾 草曾 一.致的.
  •         淘汰NullReferenceException的风险
  •         使代码更轻便、更易于维护
在C#中实现空对象模式时,关键是要确保空对象提供了故意义的默认举动,而且与真实对象的接口完全兼容。通过公道利用这种模式,可以明显进步代码的结实性和可读性。

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
回复

使用道具 举报

登录后关闭弹窗

登录参与点评抽奖  加入IT实名职场社区
去登录
快速回复 返回顶部 返回列表