我正在浏览一段 Java 代码,我看到已经使用某个接口(interface)分配了对象,并且该接口(interface)包含一些使用 new
运算符分配对象的方法。我无法想到为什么他们使用接口(interface)而不是直接使用 new
运算符分配对象。例如:
Animal animal = new Animal();
或
Animal animal = interface.allocateAnimal()
这里 interface
是一个有方法 allocateAnimal
的接口(interface),它除了
new Animal()
.
所以最终我们在做同样的事情,但方式不同,那么这里有什么收获呢?
编辑 1:实际上接口(interface)是在其他地方实现的。所以接口(interface)不包含任何实现代码,它只包含方法。
最佳答案
首先 interface
没有分配任何东西。他们只是在建立契约(Contract)。
你看到的是factory method pattern .有人决定实现该接口(interface),具体实现的方法是创建一个 Animal
对象。您可以查看该模式的链接,在那里您会找到关于工厂方法的详尽解释。
有一个question这里关于使用工厂模式的原因可能值得一试。重点是:
...using a Factory allows the consumer to create new objects without having to know the details of how they're created, or what their dependencies are - they only have to give the information they actually want.
还有更多:编写您正在阅读的代码的人可能会尝试引用一些不是 java 中的技术 interface
关键字的编程接口(interface)。这意味着 something else .
关于java - 通过 new 运算符或某些接口(interface)进行对象分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16560878/