What is the dependency inversion principle and why is it important?

前端 未结 15 1154
别那么骄傲
别那么骄傲 2020-11-28 00:06

What is the dependency inversion principle and why is it important?

15条回答
  •  感动是毒
    2020-11-28 00:52

    Dependency Inversion Principle (DIP) says that

    i) High level modules should not depend upon low-level modules. Both should depend upon abstractions.

    ii) Abstractions should never depend upon details. Details should depend upon abstractions.

    Example:

        public interface ICustomer
        {
            string GetCustomerNameById(int id);
        }
    
        public class Customer : ICustomer
        {
            //ctor
            public Customer(){}
    
            public string GetCustomerNameById(int id)
            {
                return "Dummy Customer Name";
            }
        }
    
        public class CustomerFactory
        {
            public static ICustomer GetCustomerData()
            {
                return new Customer();
            }
        }
    
        public class CustomerBLL
        {
            ICustomer _customer;
            public CustomerBLL()
            {
                _customer = CustomerFactory.GetCustomerData();
            }
    
            public string GetCustomerNameById(int id)
            {
                return _customer.GetCustomerNameById(id);
            }
        }
    
        public class Program
        {
            static void Main()
            {
                CustomerBLL customerBLL = new CustomerBLL();
                int customerId = 25;
                string customerName = customerBLL.GetCustomerNameById(customerId);
    
    
                Console.WriteLine(customerName);
                Console.ReadKey();
            }
        }
    

    Note: Class should depend on abstractions like interface or abstract classes, not specific details (implementation of interface).

提交回复
热议问题