工厂方法模式也是一种创建型模式,之前提到过创建型模式用来解耦 ”被创建的对象“和”创建对象的对象“,两者之间的关系。
既A与B的关系是使用关系,但是A并没有把B当成一个属性,因为它并不应该是A的一个属性,类似人使用苹果,但是苹果不能被作为人的一个属性。
比如对于苹果而言,是一种水果,还有很多水果,比如Banana, Orange, Peach.
人有一个方法叫eatFruit();
但是你并不能在这个方法中直接new一个fruit
因为这样太耦合,你可以把一个fruit对象作为参数传入到eatFruit方法中去,但你只不过把问题给拖延了,那这个Fruit又是从哪来的的呢?
所以最好你自带一个工厂方法FruitFactory,可以getFruit(),而这个FruitFactory就可以作为你人类的属性被注入进来。这样,我们就把创建水果和人吃水果的动作进行解耦。将水果的实例化拖延到FruitFactory工厂中去。
看,水果不能作为人的一个属性,但是水果工厂可以,这很合理。
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 
 | class Fruit{
 public int weight();
 public int color();
 }
 
 class Banana extends Fruit{
 public int weight(){
 xxxx
 }
 public int color(){
 xxxx
 }
 }
 
 class Apple extends Fruit{
 public int weight(){
 xxxx
 }
 public int color(){
 xxxx
 }
 }
 
 Interface FruitFactory{
 public Fruit getFruit();
 }
 
 class AppleFactory implements FruitFactory{
 public Fruit getFruit(){
 return new Apple();
 }
 }
 
 class BananaFactory implements FruitFactory{
 public Fruit getFruit(){
 return new Banana();
 }
 }
 
 class Person{
 private FruitFactory fruitFactory;
 
 public void eatFruit(){
 Fruit fruit = fruitFactory.getFruit();
 xxxx
 }
 
 }
 
 
 | 
使用场景
orm中建立数据库链接的那一套东西,基本都是工厂方法的。通过的ConnectionFactory 的getConnection,能获得不同类型的数据库链接对象,因为工厂方法就是定义一个创建产品对象的工厂接口,将实际工作推迟到子类中。而每种ConnectionFactory,都提供自己Connection对象创建方式。