• 已删除用户
[设计模式]依赖倒置原则
Administrator
发布于 2021-09-20 / 87 阅读 / 0 评论 / 0 点赞

[设计模式]依赖倒置原则

要针对接口编程, 不要对实现编程

描述

高层模块不应该依赖低层模块, 它们都应该依赖抽象. 抽象不应该依赖于细节,细节应该依赖于抽象.

依赖倒置原则的中心思想是面向接口编程

依赖倒置原则基于这样一个事实 : 相对于细节的多变性, 抽象的东西要稳定的多. 以抽象为基础搭建起来的架构比以细节为基础搭建起来的架构要稳定的多.

实现开闭原则的关键是抽象化,并且从抽象化导出具体化实现, 如果说开闭原则是面向对象设计的目标的话, 那么依赖倒转原则就是面向对象设计的主要手段.

实例

不推荐

using System;
namespace 依赖倒置原则001
{
    public class Book
    {
        public string GetContent()
        {
            return "很久很久以前有一个故事.";
        }
    }
	
    public class Newspaper
    {
        public string GetContent()
        {
            return "春节到了, 中国人民欢度新年.";
        }
    }
	
    public class Mother
    {
        public void Narrate(Book book)
        {
            Console.WriteLine("妈妈开始讲故事.");
            Console.WriteLine(book.GetContent());
        }
    }
	
    class Program
    {
        static void Main(string[] args)
        {
            Mother mother = new Mother();
            mother.Narrate(new Book());
        }
    }
}
using System;
namespace 依赖倒置原则002
{
    public interface IReader
    {
        string GetContent();
    }
	
    public class Book : IReader
    {
        public string GetContent()
        {
            return "很久很久以前有一个故事.";
        }
    }
	
    public class Newspaper : IReader
    {
        public string GetContent()
        {
            return "春节到了, 中国人民欢度新年.";
        }
    }
	
    public class Mother
    {
        public void Narrate(IReader reader)
        {
            Console.WriteLine("妈妈开始讲故事.");
            Console.WriteLine(reader.GetContent());
        }
    }
	
    class Program
    {
        static void Main(string[] args)
        {
            Mother mother = new Mother();
            mother.Narrate(new Book());
            mother.Narrate(new Newspaper());
        }
    }
}