Facory Pattern(工厂模式)
工厂模式分为工厂方法模式(也可以成为简单工厂)和抽象工厂模式。
例如工厂方法模式:1
2
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104    public interface Person{
       String getName();
    }
    public Class Male implements Person{
        String getName(){
            return "Male";
            }
    }
    
    public Class Female implements Person{
        String getName(){
            return "Female";
        }
    }
    
    public class PersonFacory{
        public static createPerson(int type){
            if(type==1){
                return new Male();
            }else{
                return new Female();
            }
        }
    }
```   
工厂方法模式相对比较简单,主要是接受不同的参数组装不同的bean。
抽象工厂模式,参见如下代码:
```java
    interface BlackPerson extends Person(){
        void handler(int type);
        String getColor();
    }
    
    interface YellowPerson extends Person{
        
        String getColor();
    }
    public class BlackMale extends BlackPeron{
        void handler(int type){
        }
    	public String getColor(){
    		return "black";
    	}
    	public String getName(){
    		return "blackMale";
    	}
    }
    
    public class BlackFemale extends BlackPeron{
        void handler(int type){
        }
    	public String getColor(){
    		return "BlackGirl";
    	}
    	public String getName(){
    		return "BlackFemale";
    	}
    }
    
    public class YellowMale extends YellowPeron{
    	public String getColor(){
    		return "Yellow";
    	}
    	public String getName(){
    		return "YellowMale";
    	}
    }
    
    public class YellowFemale extends YellowPeron{
    	public String getColor(){
    		return "YellowGirl";
    	}
    	public String getName(){
    		return "YellowFemale";
    	}
    }
    
    abstract ColorPersonFacory{
        BlackPerson createBlackPerson(int type);
        YellowPerson createYellowPerson(int type);
    }
    class MaleFactory implements ColorPersonFacory{
        BlackPerson createBlackPerson(int type){
           return new BlackMale();
        }
        
        YellowPerson createYellowPerson(int type){
            return new YellowMale();
        }
    }
```    
   
###Srping中实现工厂模式###
Spring中其实实现的是工厂方法模式,例如需要配置一个Male:
 
```xml 
    <bean id="male" class="PersonFacory" 
         factory-method="createPerson">
        <constructor-arg value="1" />
        <property></property>
    </bean>
其中constructor-arg的参数即是createPerson的参数,新建出bean之后,通过property对bean做属性设置。
Spring中虽然是一种工厂方法模式,但是通过配置也同样可以支持抽象工厂模式,例如通过工厂模式获取BlackMale,可以如下配置1
2
3
4
5<bean id="blackMale" class="BlackPersonFacory" 
         factory-method="createPerson">
          <constructor-arg value="1" />
         <property></property>
  </bean>