How will I know when to create an interface?

2020-01-23 02:52发布

I'm at a point in my development learning where I feel like I must learn more about interfaces.

I frequently read about them but it just seems like I cannot grasp them.

I've read examples like: Animal base class, with IAnimal interface for things like 'Walk', 'Run', 'GetLegs', etc - but I've never been working on something and felt like "Hey I should use an interface here!"

What am I missing? Why is it such a hard concept for me to grasp! I am just intimidated by the fact that I might not ever realize a concrete need for one - mostly due to some missing aspect of understanding them! It makes me feel like I'm missing something up top in terms of being a developer! If anyone has had an experience like this and had a breakthrough I would appreciate some tips on how to understand this concept. Thank you.

24条回答
爱情/是我丢掉的垃圾
2楼-- · 2020-01-23 03:13

Some non-programming examples that might help you see the appropriate uses of interfaces in programming.

There's an interface between electrical devices and the electricity network - it's the set of conventions about the shape of the plugs and sockets and the voltages/currents across them. If you want to implement a new electrical device, as long as your plug follows the rules it will be able to get services from the network. This makes extensibility very easy and removes or lowers the costs of coordination: you don't have to notify the electricity provider about how your new device works and come to a separate agreement about how to plug your new device into the network.

Countries have standard rail gauges. This allows a division of labour between engineering companies who put down rails and engineering companies who build trains to run on those rails, and it makes it possible for rail companies to replace and upgrade trains without rearchitecting the whole system.

The service a business presents to a client can be described as an interface: a well defined interface emphasises the service and hides the means. When you put a letter in a mailbox, you expect the postal system to deliver the letter within a given time but you have no expectations about how the letter is delivered: you don't need to know, and the postal service has the flexibility to choose the means of delivery that best meets the requirements and current circumstances. An exception to this is the ability of customers to choose airmail - that's not the kind of interface a modern computer programmer would have designed, since it reveals too much of the implementation.

Examples from nature: I'm not too keen on the eats(), makesSound(), moves(), etc examples. They do describe behaviour, which is correct, but they don't describe interactions and how they're enabled. The obvious examples of interfaces that enable interactions in nature are to do with reproduction, for example a flower provides a certain interface to a bee so that pollination can take place.

查看更多
Rolldiameter
3楼-- · 2020-01-23 03:13

Consider you are making a first person shooting game. The player has multiple guns to choose from.

We can have an interface Gun which defines a function shoot().

We need different subclasses of Gun class namely ShotGun Sniper and so on.

ShotGun implements Gun{
    public void shoot(){
       \\shotgun implementation of shoot.
    } 
}

Sniper implements Gun{
    public void shoot(){
       \\sniper implementation of shoot.
    } 
}

Shooter Class

The shooter has all the guns in his Armour. Lets create a List to represent it.

List<Gun> listOfGuns = new ArrayList<Gun>();

The shooter cycles through his guns,as and when needed, using the function switchGun()

public void switchGun(){
    //code to cycle through the guns from the list of guns.
    currentGun = //the next gun in the list.
}

We can set the current Gun , using the above function and simply call shoot() function, when fire() is called.

public void fire(){
    currentGun.shoot();
}

The behavior of the shoot function will vary according to different implementations of the Gun interface.

Conclusion

Create an interface, when a class function is dependent on a function from another class, which is subjected to change its behavior, based on instance(object) of the class implemented.

for e.g. fire() function from Shooter class expects guns(Sniper, ShotGun) to implement the shoot() function. So if we switch the gun and fire.

shooter.switchGun();
shooter.fire();

We have changed the behaviour of fire() function.

查看更多
forever°为你锁心
4楼-- · 2020-01-23 03:14

Use interfaces when implementations of the same functionality will differ.

Use a abstract/base classes when you need to share a common concrete implementation.

查看更多
三岁会撩人
5楼-- · 2020-01-23 03:15

You should define an interface once you need to force a behaviour for your class.

An Animal's behaviour may involve Walking, Eating, Running, etc. Therefore, you define them as interfaces.

Another practical example is the ActionListener (or Runnable) interface. You would implement them when you need to keep track of a particular event. Therefore, you need to provide the implementation for the actionPerformed(Event e) method in your class (or subclass). Similarly, for the Runnable interface, you provide the implementation for the public void run() method.

Also, you can have these interfaces implemented by any number of classes.

Another instance where Interfaces are used (in Java) is to implement the multiple inheritance offered in C++.

查看更多
男人必须洒脱
6楼-- · 2020-01-23 03:16

A code example (combination of Andrew's with an extra of mine at what-is-the-purpose-of-interfaces), that also makes a case on why interface instead of an abstract class on languages with no support for multiple inheritance (c# and java):

interface ILogger
{
    void Log();
}
class FileLogger : ILogger
{
    public void Log() { }
}
class DataBaseLogger : ILogger
{
    public void Log() { }
}
public class MySpecialLogger : SpecialLoggerBase, ILogger
{
    public void Log() { }
}

Notice that the FileLogger and DataBaseLogger doesn't need the interface (could be a Logger abstract base class). But consider you are required to use a third party logger that forces you to use a base class (lets say it exposes protected methods you Need to use). As the language doesn't support multiple inheritance you won't be able to use the abstract base class approach.

Bottom line is: use an interface when possible to get extra flexibility on your code. Your implementation is less tied, so it accomodates better for change.

查看更多
何必那么认真
7楼-- · 2020-01-23 03:17

As several people have probably already answered, interfaces can be used to enforce certain behaviors between classes that will not implement those behaviors the same way. So by implementing an interface you are saying that your class has the behavior of the interface. The IAnimal interface would not be a typical interface because Dog, Cat, Bird, etc. classes are types of animals, and should probably extend it, which is a case of inheritance. Instead, an interface would be more like animal behavior in this case, such as IRunnable, IFlyable, ITrainable, etc.

Interfaces are good for many things, one of the key things is pluggability. For example, declaring a method that has a List parameter will allow for anything that implements the List interface to be passed in, allowing the developer to remove and plug in a different list at a later time without having to rewrite a ton of code.

It is possible you'll never use interfaces, but if you're designing a project from scratch, especially a framework of some sort, you'll probably want to get familiar with them.

I would recommend reading the chapter on interfaces in Java Design by Coad, Mayfield, and Kern. They explain it a little better than the average introductory text. If you don't use Java, you can just read the beginning of the chapter, which is just mainly concepts.

查看更多
登录 后发表回答