2.2 KiB
2.2 KiB
title |
---|
Interface |
Using interfaces allows us to change our implementation in our project without breaking other parts, and only have to change the one place where the object is created.
As interfaces do not implement any logic by themselves, they are a great tool for programmers to program against a type rather than a concrete object. This is very useful in keeping code loosely coupled. This behavior of interfaces made them imperative for implementation of Design Patterns.
Interface Example:
public Interface IUserFavoriteFood
{
void AddFood();
Task<User> EatFavoriteFood(int id);
}
Interface inheritance and implementation:
public class UserHungry : IUserFavoriteFood
{
public AddFood()
{
// Implementation:
// A method to add food.
}
public Task<User> EatFavoriteFood(int id)
{
// Implementation:
// A method to Eat food by id.
}
}
Every implementation can be different:
public class AnotherUserHungry : IUserFavoriteFood
{
public AddFood()
{
// DIFFERENT Implementation:
// A method to add vegan food.
}
public Task<User> EatFavoriteFood(int id)
{
// DIFFERENT Implementation:
// A method to Eat only vegan food by id.
}
}