What does “program to interfaces, not implementations” mean?

前端 未结 7 1897
情深已故
情深已故 2020-11-22 07:41

One stumbles upon this phrase when reading about design patterns.

But I don\'t understand it, could someone explain this for me?

7条回答
  •  北海茫月
    2020-11-22 08:01

    It means that you should try to write your code so it uses an abstraction (abstract class or interface) instead of the implementation directly.

    Normally the implementation is injected into your code through the constructor or a method call. So, your code knows about the interface or abstract class and can call anything that is defined on this contract. As an actual object (implementation of the interface/abstract class) is used, the calls are operating on the object.

    This is a subset of the Liskov Substitution Principle (LSP), the L of the SOLID principles.

    An example in .NET would be to code with IList instead of List or Dictionary, so you could use any class that implements IList interchangeably in your code:

    // myList can be _any_ object that implements IList
    public int GetListCount(IList myList)
    {
        // Do anything that IList supports
        return myList.Count();
    }
    

    Another example from the Base Class Library (BCL) is the ProviderBase abstract class - this provides some infrastructure, and as importantly means all provider implementations can be used interchangeably if you code against it.

提交回复
热议问题