设计模式——控制反转&依赖注入

简介:

一、控制反转:

从简单的代码示例入手:

    /// <summary>
    /// 邮件服务类
    /// </summary>
    public class EmailService
    {
        public string SendMessage()
        {
            return "发送通知邮件";
        }
    }

    /// <summary>
    /// 邮件通知类
    /// </summary>
    public class NotifycationSystem
    {
        private EmailService service;
        public NotifycationSystem()
        {
            service = new EmailService(); //邮件通知类必须精确的知道创建和使用了哪种类型的服务,此处高耦合了。
        }
        public string InterestingEventHappened()
        {
            return service.SendMessage();
        }
    }
共两个类,一个邮件服务类,一个邮件通知类,邮件通知类依赖于邮件服务类。邮件通知类必须精确的知道创建和使用了哪种类型的服务,此处高耦合了。

改进一:在两代码块中引入抽象层,提取接口。

    /// <summary>
    /// 邮件服务接口
    /// </summary>
    public interface IMessageService
    {
        string SendMessage();
    }

    /// <summary>
    /// 邮件服务类
    /// </summary>
    public class EmailService : IMessageService
    {
        public string SendMessage()
        {
            return "发送通知邮件";
        }
    }

    /// <summary>
    /// 邮件通知类
    /// </summary>
    public class NotifycationSystem
    {
        private IMessageService service;//邮件通知类保存服务实现的接口
        public NotifycationSystem()
        {
            service = new EmailService(); 
        }
        public string InterestingEventHappened()
        {
            return service.SendMessage();
        }
    }
上面将依赖具体实现改为了依赖接口,减少了部分耦合。但是邮件服务类还是在邮件通知类内实例化的,也就是说邮件通知类还是要完全知道邮件服务类的具体细节。

改进二:将选择抽象实现的责任移到服务消费者类的外部。

    /// <summary>
    /// 第二层抽象: 服务定位器
    /// </summary>
    public interface IServiceLocator
    {
        IMessageService GetMessageService();
    }

    /// <summary>
    /// 第一层抽象:邮件服务接口
    /// </summary>
    public interface IMessageService
    {
        string SendMessage();
    }

    /// <summary>
    /// 邮件服务类
    /// </summary>
    public class EmailService : IMessageService
    {
        public string SendMessage()
        {
            return "发送通知邮件";
        }
    }

    /// <summary>
    /// 邮件通知类
    /// </summary>
    public class NotifycationSystem
    {
        private IMessageService service;//邮件通知类保存服务实现的接口。
        public NotifycationSystem(IServiceLocator locator)
        {
            service = locator.GetMessageService();//实现依赖关系被转移到类外。
        }
        public string InterestingEventHappened()
        {
            return service.SendMessage();
        }
    }
扩展一:弱类型服务定位器。

/// <summary>
    /// 第二层抽象: 服务定位器
    /// </summary>
    public interface IServiceLocator
    {
        object GetService(Type serviceType);
    }

    /// <summary>
    /// 第一层抽象:邮件服务接口
    /// </summary>
    public interface IMessageService
    {
        string SendMessage();
    }

    /// <summary>
    /// 邮件服务类
    /// </summary>
    public class EmailService : IMessageService
    {
        public string SendMessage()
        {
            return "发送通知邮件";
        }
    }

    /// <summary>
    /// 邮件通知类
    /// </summary>
    public class NotifycationSystem
    {
        private IMessageService service;//邮件通知类保存服务实现的接口。
        public NotifycationSystem(IServiceLocator locator)
        {
            service = (IMessageService)locator.GetService(typeof(IMessageService));//实现依赖关系被转移到类外。
        }
        public string InterestingEventHappened()
        {
            return service.SendMessage();
        }
    }

弱类型服务定位器使得这种模式更加灵活,因为他允许请求任意类型的服务类型。采用Type类型的参数,并返回一个非类型化的示例,也就是一个object类型对象。

扩展二:泛型方法。

    /// <summary>
    /// 第二层抽象: 服务定位器
    /// </summary>
    public interface IServiceLocator
    {
        T GetService<T>();//泛型接口
        object GetService(Type serviceType);
    }

    /// <summary>
    /// 第一层抽象:邮件服务接口
    /// </summary>
    public interface IMessageService
    {
        string SendMessage();
    }

    /// <summary>
    /// 邮件服务类
    /// </summary>
    public class EmailService : IMessageService
    {
        public string SendMessage()
        {
            return "发送通知邮件";
        }
    }

    /// <summary>
    /// 邮件通知类
    /// </summary>
    public class NotifycationSystem
    {
        private IMessageService service;//邮件通知类保存服务实现的接口。
        public NotifycationSystem(IServiceLocator locator)
        {
            service = locator.GetService<IMessageService>();//实现依赖关系被转移到类外。
        }
        public string InterestingEventHappened()
        {
            return service.SendMessage();
        }
    }
泛型方法,让依赖反转代码看上去更加高效优雅。

二、依赖注入:

1.构造函数注入:

    /// <summary>
    /// 邮件通知类
    /// </summary>
    public class NotifycationSystem
    {
        private IMessageService _service;
        public NotifycationSystem(IMessageService service)//构造函数注入
        {
            _service = service;
        }
        public string InterestingEventHappened()
        {
            return _service.SendMessage();
        }
    }
2.属性注入:

    /// <summary>
    /// 邮件通知类
    /// </summary>
    public class NotifycationSystem
    {
        private IMessageService MessageService { get; set; }
        public string InterestingEventHappened()
        {
            if (MessageService == null)
            {
                throw new InvalidOperationException("服务类型为赋值!");
            }
            return MessageService.SendMessage();
        }
    }




目录
相关文章
|
11月前
|
设计模式 消息中间件 XML
一起来学设计模式之依赖注入模式
前言 目前正在出一个设计模式专题系列教程, 篇幅会较多, 喜欢的话,给个关注❤️ ~ 本节给大家讲一下设计模式中的依赖注入模式,并结合实际业务场景给大家讲解如何使用~ 本专题的所有案例代码主要以Java语言为主, 好了, 废话不多说直接开整吧~ 依赖注入模式 Dependency Injection(依赖注入)是一种设计模式,用于解决对象之间的耦合关系问题,一个对象通常会通过New操作符显式创建出它所需要的相关对象,这样会导致对象之间高度耦合、难以重用、难以测试等问题。而Dependency Injection则是一种反向控制的思想,即对象不再直接操作其他对象,而是通过容器(例如Spring)
|
存储 PHP 容器
设计模式之————依赖注入(Dependency Injection)与控制反转(Inversion of Controller)
参考链接: 依赖注入(DI) or 控制反转(IoC) laravel 学习笔记 —— 神奇的服务容器 PHP 依赖注入,从此不再考虑加载顺序 名词解释 IoC(Inversion of Controller) 控制反转(概念) DI(Dependency Inject) 依赖注入(IoC...
1874 0
|
10天前
|
设计模式 SQL 算法
设计模式了解哪些,模版模式
设计模式了解哪些,模版模式
19 0
|
29天前
|
设计模式 Java uml
C++设计模式之 依赖注入模式探索
C++设计模式之 依赖注入模式探索
37 0
|
3月前
|
设计模式 存储 算法
Java 设计模式最佳实践:三、行为模式
Java 设计模式最佳实践:三、行为模式
|
3月前
|
设计模式 Go 开发工具
Golang设计模式——12中介模式
Golang设计模式——12中介模式
25 0
|
2月前
|
设计模式 前端开发 JavaScript
观察者模式 vs 发布-订阅模式:两种设计模式的对决!
欢迎来到前端入门之旅!这个专栏是为那些对Web开发感兴趣、刚刚开始学习前端的读者们打造的。无论你是初学者还是有一些基础的开发者,我们都会在这里为你提供一个系统而又亲切的学习平台。我们以问答形式更新,为大家呈现精选的前端知识点和最佳实践。通过深入浅出的解释概念,并提供实际案例和练习,让你逐步建立起一个扎实的基础。无论是HTML、CSS、JavaScript还是最新的前端框架和工具,我们都将为你提供丰富的内容和实用技巧,帮助你更好地理解并运用前端开发中的各种技术。
|
6天前
|
设计模式 Java 数据库
小谈设计模式(2)—简单工厂模式
小谈设计模式(2)—简单工厂模式
|
6天前
|
设计模式 Java
小谈设计模式(9)—工厂方法模式
小谈设计模式(9)—工厂方法模式
|
1月前
|
设计模式 编译器
解析器模式--设计模式
解析器模式--设计模式
17 0