静态工厂方法的实际用例? [英] Realistic use case for static factory method?

查看:89
本文介绍了静态工厂方法的实际用例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我熟悉静态工厂方法的概念和好处,如Joshua Bloch的

I'm familiar with the idea and benefits of a static factory method, as described in Joshua Bloch's Effective Java:

  • 工厂方法具有名称,因此与构造函数不同,您可以拥有多个具有相同签名的工厂方法.
  • 工厂方法不必创建新对象;他们可以返回先前创建的对象.这对于不可变对象或值对象很有用.
  • 与构造函数不同,工厂方法可以返回其返回类型的任何子类型的对象.

现在,我正在尝试为正在学习Java和OO原理的人解释静态工厂方法.她从具体场景而不是抽象中学到了最好的东西.如果她能看到工作中的模式并解决了一些问题,她就会明白.但是她发现,很难像上面那样阅读抽象的特征列表,以了解如何应用该模式.

Now I'm trying to explain static factory methods for someone who is learning Java and OO principles. She learns best from concrete scenarios instead of abstractions. If she can see the pattern at work, solving some problem, she'll get it. But she finds it harder to read an abstract list of characteristics like the above to understand how to apply the pattern.

您能帮我提出一个使用静态工厂方法的现实示例,该示例清楚地说明了它的好处,但是仍然很简单,可以向Java入门类中的某个人展示?

Can you help me come up with a realistic example of using a static factory method, that makes its benefits clear, but which is still simple enough to show someone in an introductory Java class?

这个人的确具有PL/SQL编程经验,但是从不学习OOP模式.

This person does have programming experience in PL/SQL but never got around to learning OOP patterns.

推荐答案

使用javax.swing.BorderFactory作为所有这三个点的示例.

Use javax.swing.BorderFactory as an example of all three points.

该类用于为摆动对象制作边框.这些边界对象可以很容易地重复使用,这种工厂方法可以做到这一点.这是 javadoc .该工厂是这三个方面的一个很好的例子:

This class is used to make borders for swing objects. These border objects can be easily re-used, and this factory method allows for this. Here is the javadoc. This factory is a great example of all three points:

  • 有多种具有不同名称的静态方法,例如createEmptyBorder()createEtchedBorder().
  • 这些方法将在可能的情况下返回以前创建的对象.在整个应用程序中经常使用相同的边框.
  • Border本身实际上是一个接口,因此通过此工厂创建的所有对象实际上都是实现此接口的类.
  • There are multiple static methods with different names like createEmptyBorder() and createEtchedBorder().
  • These methods will return previously created objects when possible. It's quite frequent that the same border would be used throughout an application.
  • Border itself is actually an interface, so all objects created through this factory are actually classes which implement this interface.

这篇关于静态工厂方法的实际用例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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