Factory Pattern Practice
2015-07-17 17:11
288 查看
PART 1 Background
工厂模式的精髓是分离对象的创建和使用。
开始学Java的时候,都是用new来创建对象。慢慢地,加入了多态,要new的话就要考虑去new哪一个concrete class了,然后有些对象的创建逻辑也复杂了,我们就需要将对象的创建和使用分开。
PART 2 Static Factory Method
最基本的,static factory,简单粗暴,通过一个static方法,根据传入的参数返回一个接口的不同实现。
Effective Java第一条就是讲的这个,跟住呢是static factory的advantages:
(1) unlike constructors, they have names.
(2) unlike constructors, they are not required to create a new object each time they're invoked.
(3) unlike constructors, they can return an object of any subtype of their return type.
(4) they reduce the verbosity of creating parameterized type instances.
static factory的disadvantage呢effective java 讲了两个,我这里只想列出其second one:
A second disadvantage of static factory methods is that they are not readily distinguishable from other static methods.
这时我才理解那些valueOf, getInstance这些convention就是用来reduce this disadvantage的。
PART 3 Builder Pattern
参考Effective Java, 非常有意思的一个pattern。精髓是好用、好读、immutable。
PART 4 Factory Method Pattern
wikipedia上的UML图说明了这个pattern的原理:
advantages:
disadvantages:
PART 5 Abstract Factory Pattern
PART 6 Spring和Hibernate中的工厂模式
Reference:
[1] Effective Java, 2nd edition.
工厂模式的精髓是分离对象的创建和使用。
开始学Java的时候,都是用new来创建对象。慢慢地,加入了多态,要new的话就要考虑去new哪一个concrete class了,然后有些对象的创建逻辑也复杂了,我们就需要将对象的创建和使用分开。
PART 2 Static Factory Method
最基本的,static factory,简单粗暴,通过一个static方法,根据传入的参数返回一个接口的不同实现。
Effective Java第一条就是讲的这个,跟住呢是static factory的advantages:
(1) unlike constructors, they have names.
(2) unlike constructors, they are not required to create a new object each time they're invoked.
(3) unlike constructors, they can return an object of any subtype of their return type.
(4) they reduce the verbosity of creating parameterized type instances.
static factory的disadvantage呢effective java 讲了两个,我这里只想列出其second one:
A second disadvantage of static factory methods is that they are not readily distinguishable from other static methods.
这时我才理解那些valueOf, getInstance这些convention就是用来reduce this disadvantage的。
PART 3 Builder Pattern
参考Effective Java, 非常有意思的一个pattern。精髓是好用、好读、immutable。
PART 4 Factory Method Pattern
wikipedia上的UML图说明了这个pattern的原理:
advantages:
disadvantages:
PART 5 Abstract Factory Pattern
PART 6 Spring和Hibernate中的工厂模式
Reference:
[1] Effective Java, 2nd edition.
相关文章推荐
- ROS学习(二)ROS入门简介
- RecyclerView
- 资源管理器
- hdu A Bug's Life
- 逻辑数据库设计 - 单纯的树(递归关系数据)
- 从0开始到N有多少个1
- PX2分享Android预设桌面定制与电量图标修改以及版本更改
- java学习笔记,1,java语言基础知识
- 给 vlc sdk 添加录像接口
- perl 监控单个ip调用接口的次数
- Java多线程
- MYSQL的索引类型:PRIMARY, INDEX,UNIQUE,FULLTEXT,SPAIAL 有什么区别?各适用于什么场合?
- 逻辑数据库设计 - 无视约束(谈外键)
- Redis事务
- java之最小的k个数
- C++关键字static
- 银行系统
- oracle 创建link 报 ora-01017错误
- 弹出菜单PopupMenu的使用
- ARC有效时,id和void*的显式转换