Selecting an object using a new operator or an interface

I was looking at Java code, and I saw that the objects were allocated using some interface, and this interface contains some methods of selecting objects using the new operator. I cannot understand why they used the interface instead of directly selecting objects using the new operator. eg:

 Animal animal = new Animal(); 

OR

 Animal animal = interface.allocateAnimal() 

here interface is an interface that has a allocateAnimal method that does nothing new Animal() .

So, ultimately, we do the same thing, but in a different way, so what is typing here?

EDIT 1: Actually, the interface is implemented somewhere else. Thus, the interface does not contain implementation code, it just contains methods.

+4
source share
3 answers

First of all, the interface does not emit anything. They just make contracts.

What you see is a factory method template . Someone decided to implement this interface, and a specific implementation method creates an Animal object. You can check the template link and there you will find a detailed explanation of the factory method.

There is a question here about the reasons for using the factory pattern, which it can check. Here is the item:

... using factory allows the consumer to create new objects without requiring information on how they are created, or what their dependencies are - they only need to provide the information they really want.

There is something else: the person who wrote the code you are reading might be trying to reference the programming interface of what is not a technical interface keyword in java. It means something else .

+6
source

This is a design pattern called Factory Method.

Note: although the class has an API (application programming interface), the β€œinterface” on it has a special meaning / is a keyword in Java. Since your example has an implementation of a method, it cannot be an interface.

Edit

If this is really a Java interface, then you can see the implementation of the Factory abstract design template: http://en.wikipedia.org/wiki/Abstract_factory_pattern

+4
source

I do not think that there really is any code in the interface, since the interface cannot be implemented.

However, the reason you would like to use interface.allocateAnimal () is because sometimes you don’t know which animal you want to receive from a new one. It can be a horse, dog, cat, etc.

Only at runtime do you know. Thus, the runtime object will be an implementation, for example, Cat, and the Cat object will have new Cat() , which it will return.

+2
source

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


All Articles