您的位置:首页 > 其它

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.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: