Why classes tend to be defined as interface nowadays?

前端 未结 5 621
囚心锁ツ
囚心锁ツ 2020-12-17 16:16

These 2-3 last years, many projects I see, like Cuyahoga open source C# CMS, tends to define persistent and non persistent classes as Interface. Why? Is there a

5条回答
  •  轮回少年
    2020-12-17 17:00

    First of all, you can't define a class as an interface. Your class implements an interface.

    Interfaces are used as one way to enable polymorphic behavior. Each class that implements the interface is free to specify its own implementation of the methods defined in the interface. Take the following for example:

    You are writing banking software. Your task is to write a Transaction Processor. Now, you know you need to handle different kinds of Transactions (Deposits, Withdraws, Transfers). You could write code that looks like:

    public class TransactionProcessor
    {
        public void ProcessDeposit( // Process Deposit );
        public void ProcessWithdraw( // Process Withdraw );
        public void ProcessTransfer( // Process Transfer );
    }
    

    And then every time somebody adds a new Transaction type, you have to modify your class. Or, you could:

    public interface ITransaction { void Process(); }
    
    public class TransactionProcessor
    {
        public void ProccessTransaction(ITransaction t) { t.Process(); }
    }
    

    Now you don't need to modify your code to Process a new type of transaction. You just need people to create their own class that implements ITransaction and your class will "just handle it".

    This allows you to swap implementations of an interface depending on your needs. It also enables things like Dependency Injection and Mocking Frameworks for Unit Testing.

    In general though, it really is just another way to make your code more flexible.

提交回复
热议问题