Is a function of interfaces mainly for using functions without knowing how to create a class?

Since I understand interfaces, they are contracts, I interpret them as a word of a contract, i.e. must have what is specified in the interface (ex open, close, read, write for files with the interface).

But what they find difficult to learn is why you need to have an interface that tells you what the class should do in general, don’t you know that since you wrote it in the interface specification?

The only reason I can see the interfaces is because of the large projects in which you want to be able to use the class without knowing how it is built. After seeing what the interface requires, you can learn how to use it.

This makes me wonder why I should use (or, if I should) interfaces in projects that I will work on. I am sure there are more uses for him that I do not see.

I took most of my assumptions and interpretations from this question and this vbforums post

+3
source share
10 answers

Suppose you are writing a set of classes that implement weapons. You may have a gun, rifle and machine gun. Then, suppose you decide to use these classes so that you execute the fire () action on each of these guns. You can do it as follows:

private Pistol p01;
private Pistol p02;
private Rifle  r01;
private MachineGun mg01;

public void fireAll() {
    p01.fire();
    p02.fire();
    r01.fire();
    mg01.fire();
}

, , . , , , : .

, , " ". .

private Firearm[] firearms;

public void fireAll() {
    for (int i = 0; i < firearms.length; ++i) {
        firearms[i].fire();
    }
}

, ?

+1

, , .

: Java. - . : ArrayList LinkedList. -, . , ArrayList O (1) () , LinkedList O (n).

, O (1) O (n), Big O.

, (.. , API), :

  • : , ( ) ;
  • , .
+4

, , , . model-view-controller.

, , GUI, . , , , " So-and-So" .

User logOut, , logOut, , . - logOut :

// Bad!
public void logOut() {
    userNameLabel.setText("Nobody is logged in");
    userProfileWindow.close();
}

, User . , User . userProfileWindow userProfileWindow, userProfileWindow , ( ).

- UserListener loggedOut, User . , , , .

public class User {
    // We'll keep a list of people who want to be notified about logouts. We don't know
    // who they are, and we don't care. Anybody who wants to be notified will be
    // notified.
    private static List<UserListener> listeners;

    public void addListener(UserListener listener) {
        listeners.add(listener);
    }

    // This will get called by... actually, the User class doesn't know who calling
    // this or why. It might be a MainMenu object because the user selected the Log Out
    // option, or an InactivityTimer object that hasn't seen the mouse move in 15
    // minutes, who knows?
    public void logOut() {
        // Do whatever internal bookkeeping needs to be done.
        currentUser = null;

        // Now that the user is logged out, let everyone know!
        for (UserListener listener: listeners) {
            listener.loggedOut(this);
        }
    }
}

// Anybody who cares about logouts will implement this interface and call
// User.addListener.
public interface UserListener {
    // This is an abstract method. Each different type of listener will implement this
    // method and do whatever it is they need to do when the user logs out.
    void loggedOut(User user);
}

// Imagine this is a window that shows the user name, password, e-mail address, etc.
// When the user logs out this window needs to take action, namely by closing itself so
// this information isn't viewable by other users. To get notified it implements the
// UserListener interface and registers itself with the User class. Now the User.logOut
// method will cause this window to close, even though the User.java source file has no
// mention whatsoever of UserProfileWindow.
public class UserProfileWindow implements UserListener {
    public UserProfileWindow() {
        // This is a good place to register ourselves as interested observers of logout
        // events.
        User.addListener(this);
    }

    // Here we provide our own implementation of the abstract loggedOut method.
    public void loggedOut(User user) {
        this.close();
    }
}

:

  • , . userProfileWindow.
  • userProfileWindow UserListener.
  • 15 .
  • InactivityTimer User.logOut.
  • User.logOut , currentUser. , - , .
  • User.logOut , loggedOut() .
  • userProfileWindow loggedOut(), .

, User , . , , , . , , , User .

, , . , , , .

+3

, , - , , , , , , ?

, . Interface. , Interface Class Interface.

+2

, . . , , , . , , , , , Gorilla , ICrushable...

interface ICrushable
{
  void MakeCrushingSound();
}

ICrushable, - ICrushable, ICrushable Car and Gorilla...

public class Crusher
{
  public void Crush(ICrushable target)
  {
    target.MakeCrushingSound();
  }
}

public class Car : ICrushable
{
    public void MakeCrushingSound()
    {
        Console.WriteLine("Crunch!");
    }
}

public class Gorilla : ICrushable
{
    public void MakeCrushingSound()
    {
        Console.WriteLine("Squish!!");
    }
}

static void Main(string[] args)
{
  ICrushable c = new Car();      // get the ICrushable-ness of a Car
  ICrushable g = new Gorilla();  // get the ICrushable-ness of a Gorilla

  Crusher.Crush(c);
  Crusher.Crush(g);
}

! , "Crunch!". "Squish!". ( ).

- ... , (IComparable). , .

: , , Gorillas. -, -, , , (, - Gorillas ... ). ICompararble...

public class Gorilla : ICrushable, IComparable
{
    public int Weight
    {
        get;
        set;
    }

    public void MakeCrushingSound()
    {
        Console.WriteLine("Squish!!");
    }

    public int CompareTo(object obj)
    {
        if (!(obj is Gorilla))
        {
            throw (new ArgumentException());
        }

        var lhs = this;
        var rhs = obj as Gorilla;

        return (lhs.Weight.CompareTo(rhs.Weight));
    }

}

, "" , . , . , , , 10 , (Array.Sort, Array.BinarySearch). ...

var gorillas = new Gorilla[] { new Gorilla() { Weight = 900 },
                               new Gorilla() { Weight = 800 },
                               new Gorilla() { Weight = 850 }
};

Array.Sort(gorillas);
var res = Array.BinarySearch(gorillas, 
    new Gorilla() { Weight = 850 });

My Gorillas , Gorilla 850.

+1

- , , . , , , , , .

Java , ( ). .

0

, . , . , , , , , , - / ? , ? , , ? . , b/w.

0

: , , , . sub System.Array, System.ArrayList, System.Collection.CollectionBase, List of T, IList. , . , IList . .

public sub DoSomething ( byval IList) end sub

, IList, IEnumerable, , .

, .

0

, ? ? , :)

++, , ... , , :

template <typename T>
void fun(const T& anObjectOfAnyType)
{
    anyThing.anyFunction();
}

, anyFunction... , , - T , ...

. , , anyFunction, , , , , . ! , .

, ? , , , , .

, , , java , , , , , . :)

,

0

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


All Articles