工廠模式主要是 爲了建立對象而提供的接口。java
1. 以下是一個簡單的工廠類app
·········10········20········30········40········50········60········70········80········90········100·······110·······120·······130·······140·······150
- public class Factory{
-
- public static Sample creator(int which){
-
- //getClass 產生Sample 通常可以使用動態類裝載裝入類。
- if (which==1)
- return new SampleA();
- else if (which==2)
- return new SampleB();
-
- }
-
- }
在程序中,若是要實例化Sample時.就使用 Sample sampleA=Factory.creator(1) 就可。spa
2.以下是更高一點的 抽象工廠模式。 若是建立對象的方法變得複雜了,如上面的是建立一個Sample對象,.net
這邊要是還要在建立一個新的對象,就能夠用這種模式了!對象
這裏假設:Sample有兩個concrete類SampleA和SamleB,而Sample2也有兩個concrete類Sample2A和SampleB2blog
那麼,咱們就將上例中Factory變成抽象類,將共同部分封裝在抽象類中,不一樣部分使用子類實現。接口
eg:ip
·········10········20········30········40········50········60········70········80········90········100·······110·······120·······130·······140·······150
- public abstract class Factory{
-
- public abstract Sample creator();
-
- public abstract Sample2 creator(String name);
-
- }
-
- public class SimpleFactory extends Factory{
-
- public Sample creator(){
- .........
- return new SampleA
- }
-
- public Sample2 creator(String name){
- .........
- return new Sample2A
- }
-
- }
-
- public class BombFactory extends Factory{
-
- public Sample creator(){
- ......
- return new SampleB
- }
-
- public Sample2 creator(String name){
- ......
- return new Sample2B
- }
-
- }