Factory Pattern Practice

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.
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值