Factory methods are static methods that return an instance of the native class(保护CONSTRUCTOR)
2016-02-04 14:00
381 查看
Factory methods are static methods that return an instance of the native class. Examples in the JDK:
LogManager.getLogManager
Pattern.compile
Collections.unmodifiableCollection, Collections.synchronizeCollection ,
and so on
Calendar.getInstance
Factory methods:
have names, unlike constructors, which can clarify code.
do not need to create a new object upon each invocation - objects can be cached and reused, if necessary.
can return a subtype of their return type - in particular, can return an object whose implementation class is unknown to the caller. This is a very valuable and widely used feature in many frameworks which use interfaces
as the return type of static factory methods.
Common names for factory methods include getInstance and valueOf.
These names are not mandatory - choose whatever makes sense for each case.
Example
LogManager.getLogManager
Pattern.compile
Collections.unmodifiableCollection, Collections.synchronizeCollection ,
and so on
Calendar.getInstance
Factory methods:
have names, unlike constructors, which can clarify code.
do not need to create a new object upon each invocation - objects can be cached and reused, if necessary.
can return a subtype of their return type - in particular, can return an object whose implementation class is unknown to the caller. This is a very valuable and widely used feature in many frameworks which use interfaces
as the return type of static factory methods.
Common names for factory methods include getInstance and valueOf.
These names are not mandatory - choose whatever makes sense for each case.
Example
public final class ComplexNumber { /** * Static factory method returns an object of this class. */ public static ComplexNumber valueOf(float aReal, float aImaginary) { return new ComplexNumber(aReal, aImaginary); } /** * Caller cannot see this private constructor. * * The only way to build a ComplexNumber is by calling the static * factory method. */ private ComplexNumber(float aReal, float aImaginary) { fReal = aReal; fImaginary = aImaginary; } private float fReal; private float fImaginary; //..elided }
相关文章推荐
- 2月4学习概况
- C语言之将无符号字符型转化为ascii码值
- C语言之将无符号字符型转化为ascii码值
- C语言之将无符号字符型转化为ascii码值
- POJ 2251 Dungeon Master
- 网上图书商城项目学习笔记-026添加一级分类
- 最熟悉的路,莫过于归途
- android:configChanges属性描述
- install Python 3.3 on Ubuntu 12.04
- 【一】基本概念
- IIS中查看W3WP.exe进程对应的应用程序池的方法
- 从零开始学习Git
- 用UITextView加载rtfd文件
- arguments详解
- Android关闭输入法键盘
- ViewHolder写法
- 电商数据库网摘
- 2016年,新的开始
- USACO 5.1.1凸包
- 微信几处比较难的引用