What is the value of interfaces?

Sorry to ask a general question, but I studied them, and besides the fact that the main programming conveys which member MUST be in the class, I just don't see any advantages.

+3
source share
10 answers

There are two (main) parts of object-oriented programming that give beginners problems; the first - inheritanceand the second - composition. These are the hardest to get; and once you understand that everything else is just a lot easier.

What do you mean, compositionfor example, what does a class do? If you follow the path of inheritance, it comes from an abstract class (say DogIS A Animal). If you use the composition, then you establish a contract (AA HAS A Driver / Loan / Insurance). Anyone who implements your interface should implement the methods of this interface.

This allows you to freely engage; and does not bind you to the model of inheritance, where it does not fit.

If inheritance is appropriate, use it; but if the relationship between the two classes is contractual or HAS-Avs. IS-Athen use the interface to simulate this part.

Why use interfaces?

-. ; . , - , , , .

:

public interface IUserRepository 
{
    public void Save();
    public void Delete(int id);
    public bool Create(User user);
    public User GetUserById(int id);
}

:

public class UserRepository : IRepository
{
    public void Save()
    {
         //Implement
    }

    public void Delete(int id)
    {
         //Implement
    }

    public bool Create(User user)
    {
         //Implement
    }
    public User GetUserById(int id)
    {
         //Implement
    }

}

, . Linq-To-SQL SQL , , IUserRepository, ; , , , .

:

. , , , .

+7

, , , . , , , , - , , , , . , , " , - //".

public interface ICar
{
    public bool EngineIsRunning{ get; }
    public void StartEngine();
    public void StopEngine();
    public int NumberOfWheels{ get; }
    public void Drive(string direction);
}

public class SportsCar : ICar
{
    public SportsCar
    {
        Console.WriteLine("New sports car ready for action!");
    }

    public bool EngineIsRunning{ get; protected set; }

    public void StartEngine()
    {
        if(!EngineIsRunning)
        {
            EngineIsRunning = true;
            Console.WriteLine("Engine is started.");
        }
        else
            Console.WriteLine("Engine is already running.");
    }

    public void StopEngine()
    {
        if(EngineIsRunning)
        {
            EngineIsRunning = false;
            Console.WriteLine("Engine is stopped.");
        }
        else
            Console.WriteLine("Engine is already stopped.");
    }

    public int NumberOfWheels
    {
        get
        {
            return 4;
        }
    }

    public void Drive(string direction)
    {
        if (EngineIsRunning)
            Console.WriteLine("Driving {0}", direction);
        else
            Console.WriteLine("You can only drive when the engine is running.");
    }
}

public class CarFactory
{
    public ICar BuildCar(string car)
    {
        switch case(car)
            case "SportsCar" : 
                return Activator.CreateInstance("SportsCar");
            default :
                /* Return some other concrete class that implements ICar */
    }
}

public class Program
{
    /* Your car type would be defined in your app.config or some other
     * mechanism that is application agnostic - perhaps by implicit
     * reference of an existing DLL or something else.  My point is that
     * while I've hard coded the CarType as "SportsCar" in this example,
     * in a real world application, the CarType would not be known at 
     * design time - only at runtime. */
    string CarType = "SportsCar";

    /* Now we tell the CarFactory to build us a car of whatever type we
     * found from our outside configuration */
    ICar car = CarFactory.BuildCar(CarType);

    /* And without knowing what type of car it was, we work to the 
     * interface.  The CarFactory could have returned any type of car,
     * our application doesn't care.  We know that any class returned 
     * from the CarFactory has the StartEngine(), StopEngine() and Drive()
     * methods as well as the NumberOfWheels and EngineIsRunning 
     * properties. */
    if (car != null)
    {
        car.StartEngine();
        Console.WriteLine("Engine is running: {0}", car.EngineIsRunning);
        if (car.EngineIsRunning)
        {
            car.Drive("Forward");
            car.StopEngine();
        }
    }
}

, , ICar, , . , - , CarFactory.BuildCar(). "DragRacer" , , , , , DragRacer ICar, .

IDataStore, , - , -, , - , , , factory, IDataStore, .

( .NET) , , , , , , ICar, DLL , .

+5

, , .

(++ - ) ; (, , ).

, Java #, , , , , --. .

, , , - , , , , .

+2

, :

+1

.

, , , - , . , , - , .

+1

Java, , , , , " ", .

, , , , ( , ) , t , , .

... Java. .

, . . 2 . http . 10 , USB.

, .

    interface writeable
    {
       void open();
       void write();
       void close();
    }

    class A : HTTP_CONNECTION implements writeable
    {
        //here, opening means opening an HTTP connection.
        //maybe writing means to assemble our message for a specific protocol on top of 
        //HTTP
        //maybe closing means to terminate the connection
    }

    class B : USB_DEVICE implements writeable
    {
        //open means open a serial connection
        //write means write the same message as above, for a different protocol and device
        //close means to release USB object gracefully.
    }
0

Java , . , , , .

0

. . , , ( ) .

0

Electron .

- . - . - /, . .

, , , . ?

.

.

, , . , , .

Motorcar , ? , , , , Motorcar. , Motorcar. ? , - ?

, . - . , , .

, , , / , , - .

, , , - .

interface Transportation
{
  takePassengers();
  gotoDestination(Destination d);
}

class Motorcar implements Transportation
{
  cleanWindshiedl();
  getOilChange();
  doMillionsOtherThings();
  ...
  takePassengers();
  gotoDestination(Destination d);
}

class Kayak implements Transportation
{
  paddle();
  getCarriedAcrossRapids();
  ...
  takePassengers();
  gotoDestination(Destination d);
}

, , .

Transportation.takePassengers or
Transportation.gotoDestination

, . , . , , , .

, AntiGravityCar. , , , , , , AntiGravityCar. , , , , , , , , ado.

0

: . , Foo, ", Foo" , . " ", " , "; , , . . A VolkswagonBeetleConvertible VolkswagonBeetle, a FordMustangConvertible FordMustang. VolkswagonBeetleConvertible, FordMustangConvertible IOpenableTop, . , ", IOpenableTop".

0
source

Source: https://habr.com/ru/post/1723710/


All Articles