设计模式-工厂方法模式

1. 为什么需要工厂方法模式:

   工厂方法模式意在分离产品与创建的两个层次,使得用户在一个工厂池中科院选择想使用的产品,而忽略其创建过程。

进一步说,就像一个大型工厂,对消费者而言,只需知道都有什么工厂的产品生产出来,而不必关注产品是如何生产的,但对于工厂来说,需要知道产品的制造过程。

2.模式角色与类结构图

 

 

  Creator: 创建工厂的接口

  ConcreteCreator: 具体产品实现

  Produce 产品接口

  ConcreteProduct :具体产品实现

3.适用场景

      1 当一个类不知道它所必须创建的对象的类的时候。

  2 当一个类希望由他的子类来制定它所创建的对象的时候

  3 当类创建对象的职责委托给多个帮助子类中的某一个,并且希望进行一些信息的局部初始化的时候。

4.实际应用

应用场景:
1.JDK中Calendar的getInstance方法
2.Spring中IOC容器创建管理bean对象
3.Hibernate中SessionFactory创建Session
4.JDBC中Connection对象的获取
5.XML解析时DocumentBuilderFactory创建解析工厂
6.反射中Class对象的newInstance()

 1 package org.factory.factorymethod;
 2 
 3 public interface CarFactory {
 4     Car createCar();
 5 }
 6 
 7 package org.factory.factorymethod;
 8 
 9 public interface Car {
10     void run();
11 }
12 
13 public class AudiFactory implements CarFactory {
14 
15     @Override
16     public Car createCar() {
17         // TODO Auto-generated method stub
18         return  new Audi();
19     }
20 
21 }
22 
23 public class BydFactory implements CarFactory {
24 
25     @Override
26     public Car createCar() {
27         // TODO Auto-generated method stub
28         return  new Byd();
29     }
30 
31 }
32 
33 public class BenzFactory implements CarFactory {
34 
35     @Override
36     public Car createCar() {
37         // TODO Auto-generated method stub
38         return new Benz();
39     }
40 
41 }
42 
43 public class Audi implements Car {
44 
45     @Override
46     public void run() {
47         // TODO Auto-generated method stub
48         System.out.println("奥迪再跑!");
49     }
50 
51 }
52 
53 public class Benz implements Car {
54 
55     @Override
56     public void run() {
57         // TODO Auto-generated method stub
58         System.out.println("奔驰再跑!");
59     }
60 
61 }
62 
63 public class Byd implements Car {
64 
65     @Override
66     public void run() {
67         // TODO Auto-generated method stub
68         System.out.println("比亚迪再跑!");
69     }
70 
71 }
72 
73 package org.factory.factorymethod;
74 
75 public class Client {
76 
77     public static void main(String[] args) {
78         // TODO Auto-generated method stub
79         Car c1 = new AudiFactory().createCar();
80         Car c2 = new BydFactory().createCar();
81         
82         c1.run();
83         c2.run();
84     }
85 
86 }
View Code

 

posted on 2015-11-04 20:37  ilinux_one  阅读(210)  评论(0编辑  收藏  举报

导航