为什么使用工厂而不是“新”? [英] Why use a factory instead of 'new'?

查看:191
本文介绍了为什么使用工厂而不是“新”?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在读这本书 EMF:Eclipse建模框架,其中说明:

I am reading the book EMF: Eclipse Modeling Framework where its stated:


EMF编程模型强烈地鼓励但不要求使用工厂创建对象的
。而不是简单地使用
new运算符来创建[对象] ...

The EMF programming model strongly encourages, but doesn’t require, the use of factories for creating objects. Instead of simply using the new operator to create [an object]...

为什么鼓励使用工厂超过

Why is the use of factories encouraged over new?

您的答案不一定是EMF具体的,只要它必须

推荐答案

您可以阅读有效的Java项目1:考虑静态工厂方法而不是构造函数。它详细描述了使用工厂方法的优点:

You can read Effective Java Item 1: Consider static factory methods instead of constructors. It describes advantages of using factory methods in detail:


  • 静态工厂方法的一个优点是,与构造函数不同,它们为
    有名称

  • One advantage of static factory methods is that, unlike constructors, they have names

静态工厂方法的第二个优点是,与构造函数不同,
每次都不需要创建一个新对象它们被调用。

A second advantage of static factory methods is that, unlike constructors, they are not required to create a new object each time they’re invoked.

静态工厂方法的第三个优点是,与构造函数不同,
可以返回其对象的任何子类型返回类型

A third advantage of static factory methods is that, unlike constructors, they can return an object of any subtype of their return type.

静态工厂方法的第四个优点是它们减少创建参数化类型实例的冗长度(似乎自Java 7以来已经过时) p>

A fourth advantage of static factory methods is that they reduce the verbosity of creating parameterized type instances (seems to be outdated since Java 7)

这篇关于为什么使用工厂而不是“新”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆