When do I use abstract classes versus interfaces with regards to dependency Injection?

前端 未结 6 928
名媛妹妹
名媛妹妹 2021-02-08 18:23

I have been reading some articles about the SOLID principles and dependency Inversion. From my point of view, I must use an interface to talk to any class. My classes are chatti

6条回答
  •  醉梦人生
    2021-02-08 19:09

    Abstract classes here to fight with duplicated code. Interfaces - to define contracts (API).

    Depend on interfaces - they simply describe contract (API) of dependency, and they can by mocked easily. So, start with interface:

    public interface IMessage
    {
        void Get(); // modifiers like public are not allowed here
        void Send();
    }
    

    And here is your dependent class, which should depend only on abstraction (i.e. interface):

    public class MessageManager
    {
        private IMessage _message;
    
        // depend only on abstraction 
        // no references to interface implementations should be here
        public IMessage Message
        {
            get { return _message; }
            set { _message = value; }
        }
    
        public MessageManager(IMessage message)
        {
            _message = message;
        }
    }
    

    Then create class, which will implement your interface:

    public class Sms : IMessage
    {
        // do not use explicit implementation 
        // unless you need to have methods with same signature
        // or you want to hide interface implementation
        public void Get()
        {
            Console.WriteLine("Message Get!");
        }
    
        public void Send()
        {
            Console.WriteLine("Message Send!");
        }
    }
    

    Now you have inversed dependencies - MessageManager and Sms depend only on IMessage. You can inject any IMessage implementations to MessageManager (MessageManager now fit OCP - open for extension, but closed for modification).

    Create base abstract message class only when you have duplicated code in several IMessage implementors. When you create abstract class (place, where you move duplicated code), you should not change interface, because contract stays the same. Just inherit your base class from original IMessage interface.

提交回复
热议问题