工厂方法——Factory Method
来源:互联网 发布:浪潮数据库服务器 编辑:程序博客网 时间:2024/06/08 10:11
工厂方法是一个能够返回实例对象的静态方法,在JDK中有以下几个例子使用到:
LogManager.getLogManager
Pattern.compile
Calendar.getInstance
工厂方法的好处:
1.具有名字,使得代码更优雅,不像构造器。
2.不一定每次都产生一个新的对象,如果必要的话,原来的对象可以被存储。
3.可以返回定义类型的子类对象。尤其是可以返回实现了定义接口但对调用者来说未知 的一个类(这个类implements 一个interface,但是个什么样的类,对调用者来说是未知的)。因此,框架往往用interface来作为工厂方法的返回类型。
一般的方法名称为,getInstance 和 valueOf。
Example:
public final class ComplexNumber { private float fReal; private float fImaginary; /** * 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; } //..elided}
0 0
- 工厂方法模式——Factory Method
- 工厂方法——Factory Method
- Factory Method 工厂方法
- 工厂方法factory method
- 工厂方法Factory Method
- 工厂方法,Factory Method
- 工厂方法(Factory Method)
- 工厂方法(Factory Method)
- 工厂方法 Factory Method
- 工厂方法(Factory Method)
- 设计模式——工厂方法模式【Factory Method Pattern】
- 设计模式——工厂方法Factory Method
- 【设计模式】Factory Method Pattern——工厂方法模式
- C#设计模式——工厂方法模式(Factory Method)
- Java设计模式 —— 工厂方法模式 (Factory Method)
- 软件设计模式——工厂方法模式(Factory Method)
- Java设计模式——工厂方法(Factory Method)
- 设计模式(3)——工厂方法 Factory Method
- 收集的linux远程ssh连接putty失败解决办法!
- Exception from container-launch: org.apache.hadoop.util.Shell$ExitCodeException
- hdu1045
- jquery.fn.extend与jquery.extend
- UIActivityIndicatorView
- 工厂方法——Factory Method
- 三个小招式,教你优雅地对付霸占你电脑的熊孩子
- PHP安装包TS和NTS的区别
- hibernate 使用mysql6.0 无法自动建表的解决办法
- 【android】解决Viewpager设置高度为wrap_content无效的方法
- 想成为优秀产品经理?别忽视这十本好书
- 【Qt】仿QQ表情选择控件
- HDU-#1115 Lifting the Stone(多边形重心)
- 什么是IT