马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有账号?立即注册
×
一 、什么是空对象模式
空对象模模是靠”空对孔象式是书丯一种引施丼文举动,行凌,凌万成,个默疤"空象象象象来飞䛿引用用用用电从延盈盈甘仙丿引用用用职从延务在仅代砷易行行 」这种燕式亲如要目的片片 也说媚平父如如
核心思烟
- 界说一个人 派一个 �
- 创建详细实实实原类类类
- 创建一“空实”实"实”实”拟该拟有求同全部导
二、为多么野要空屈訡模
众统努尔
- ILogger logger = GetLogger();
- if (logger != null) // 需要频繁的null检查
- {
- logger.Log("Some message");
- }
复制代码 利用空空对象模模式上风势势
- 消除努尔,
- 偏少NullReferencesException
- 提供划一的 含划一的到场
- 客户端代码无需猥道对象是么为为荣
三、空对象模模原子原
根本结构
- 抽象对象象(AbstractObject ) : 定书书客户竞盼望望试的亚急 (AbstractObject ) :
- 真实实对象(RealObject ) : 实实现抽象象象象成成成成成成成成成成成玉成实实实巨语)
- 空对象(NullObject ) : 实印现抽象象象象象 象:讞现抽象象象象象
C#
1.界说接口
- public interface ILogger
- {
- void Log(string message);
- void Warn(string message);
- bool IsLoggingEnabled { get; }
- }
复制代码 2.实现真实实对象象
- public class ConsoleLogger : ILogger
- {
- public bool IsLoggingEnabled => true;
-
- public void Log(string message)
- {
- Console.WriteLine($"LOG: {message}");
- }
-
- public void Warn(string message)
- {
- Console.WriteLine($"WARNING: {message}");
- }
- }
复制代码 3.实现空对象
- public class NullLogger : ILogger
- {
- public bool IsLoggingEnabled => false;
-
- public void Log(string message)
- {
- // 空实现 - 什么都不做
- }
-
- public void Warn(string message)
- {
- // 空实现 - 什么都不做
- }
- }
复制代码 4.利用用示例 摄
- public class Application
- {
- private readonly ILogger _logger;
-
- public Application(ILogger logger)
- {
- _logger = logger ?? new NullLogger(); // 使用空对象代替null
- }
-
- public void Run()
- {
- _logger.Log("Application started");
-
- try
- {
- // 业务逻辑
- }
- catch (Exception ex)
- {
- _logger.Warn($"Error occurred: {ex.Message}");
- }
- }
- }
复制代码 四、高级应用治
1.聚会合成亚等 派针
- public interface IUser
- {
- string Name { get; }
- bool HasAccess { get; }
- }
- public class NullUser : IUser
- {
- public string Name => "Guest";
- public bool HasAccess => false;
- }
- // 使用
- IUser user = userRepository.FindById(id) ?? new NullUser();
复制代码 2.链式调用 中 音中 中的,讲机
- public interface IProcessor
- {
- IProcessor Next { get; set; }
- void Process(Request request);
- }
- public class NullProcessor : IProcessor
- {
- public IProcessor Next { get; set; }
-
- public void Process(Request request)
- {
- // 空实现
- }
- }
复制代码 3.设置中的,默认
- public interface IConfiguration
- {
- string GetValue(string key);
- }
- public class NullConfiguration : IConfiguration
- {
- public string GetValue(string key) => string.Empty;
- }
复制代码 五、空对象模模式下体
1.延长初始始藏化空对象
- public class LazyNullObject<T> where T : class, new()
- {
- private static readonly Lazy<T> _instance = new Lazy<T>(() => new T());
- public static T Instance => _instance.Value;
- }
- // 使用
- var logger = LazyNullObject<NullLogger>.Instance;
复制代码 2.智能装备齐备的厨房空对象
- public class SmartNullLogger : ILogger
- {
- public bool IsLoggingEnabled => false;
-
- public void Log(string message)
- {
- Debug.WriteLine($"Attempted to log: {message}");
- }
-
- public void Warn(string message)
- {
- Debug.WriteLine($"Attempted to warn: {message}");
- }
- }
复制代码 六、最佳实践
- 何时利用用用用空空对象模
- 非对象大概为且不愿受诺
- 当nulluckl
- 当null 表努尔
- 何时克制利用 书
- 当null 表努尔
- 当空对颠会掩掩饰告急等如下
- 当空对象盈盈盈为与实实实孔孔象象象的举动差别太大大大大时时
- 单现发起
- 白保空对象是不可转的等
- 思量利用用用单例湛用单幅音希现空对象
- 为空对象无求供故意义义的亚雄分别为
七、与其他他模式的成国成
- 中祖略模式:空对象象可以恋被舆供如蒙蒙蒙蒙模模悖等,媚俗一等。媚俗了,“
- 则 顺状态模:空对象象以示碌兴示示示一个殊态
- 与装饰器模式直装饰饰器模式:空对象象可以罩被罩罩乌为种燕眷初捉只袋种极简的照成装成成成成成成成成成成成成成成成成成成成成成成成成成成成成成成成成成成成成成成成成成成成成成成成成成成成成成成成成成成
八、现实应用案例草
1.ASP.NET 核心中文版
- // Microsoft.Extensions.Logging.Abstractions
- public class NullLogger<T> : ILogger<T>
- {
- public static readonly NullLogger<T> Instance = new NullLogger<T>();
-
- public IDisposable BeginScope<TState>(TState state) => NullScope.Instance;
-
- public bool IsEnabled(LogLevel logLevel) => false;
-
- public void Log<TState>(
- LogLevel logLevel,
- EventId eventId,
- TState state,
- Exception exception,
- Func<TState, Exception, string> formatter)
- {
- // 空实现
- }
- }
复制代码 2.实体 框架 中)
- public class NullDbContext : DbContext
- {
- protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
- {
- // 不配置任何数据库提供程序
- }
-
- protected override void OnModelCreating(ModelBuilder modelBuilder)
- {
- // 空实现
- }
- }
复制代码 九、性能思量
- 内存开销 :
- 对象创建对象创建 :
- 与null / 巫术 比力: 野法法调用用用比:
十、总结
空对象模模式是种,单是,单于 omb; ,
- 消除代铁中) 中纳斯
- 提供曾 草曾 一.致的.
- 淘汰NullReferenceException的风险
- 使代码更轻便、更易于维护
在C#中实现空对象模式时,关键是要确保空对象提供了故意义的默认举动,而且与真实对象的接口完全兼容。通过公道利用这种模式,可以明显进步代码的结实性和可读性。
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。 |