時間緊迫,關於工廠模式的內容有點多,要講的話大致分為簡單工廠模型,工廠方法模型,抽象工廠模型
這里 ,我就大概講一下簡單工廠模型,也是我們實際開發中用的相對比較多的
第一步,先創建工廠接口,也就是規定這個工廠是干嘛的:
1 /* 2 * 創 建 者: ouyangshengduo 3 * 創建時間: 2017年3月31日 4 * 文件名稱: HairInterface.java 5 * 版權信息: 2017 Edan. All rights reserved. 6 * 文件描述: 發型接口 7 */ 8 package com.oysd.model.factory; 9 10 public interface HairInterface { 11 12 //實現了發型 13 public void draw(); 14 15 }
第二步,實現不同產品具體內容
1 /* 2 * 創 建 者: ouyangshengduo 3 * 創建時間: 2017年3月31日 4 * 文件名稱: LeftHair.java 5 * 版權信息: 2017 Edan. All rights reserved. 6 * 文件描述: 7 */ 8 package com.oysd.model.factory; 9 10 public class LeftHair implements HairInterface { 11 12 /** 13 * 畫一個左偏分發型 14 */ 15 @Override 16 public void draw() { 17 // TODO Auto-generated method stub 18 19 System.out.println("-----------實現了一個左偏分發型-----------"); 20 } 21 22 }
1 /* 2 * 創 建 者: ouyangshengduo 3 * 創建時間: 2017年3月31日 4 * 文件名稱: RightHair.java 5 * 版權信息: 2017 Edan. All rights reserved. 6 * 文件描述: 7 */ 8 package com.oysd.model.factory; 9 10 public class RightHair implements HairInterface { 11 12 13 /** 14 * 畫一個右偏分的發型 15 */ 16 @Override 17 public void draw() { 18 // TODO Auto-generated method stub 19 System.out.println("-----------實現了一個右偏分發型-----------"); 20 } 21 22 }
創建工廠類
1 /* 2 * 創 建 者: ouyangshengduo 3 * 創建時間: 2017年3月31日 4 * 文件名稱: HairFactory.java 5 * 版權信息: 2017 Edan. All rights reserved. 6 * 文件描述: 7 */ 8 package com.oysd.model.factory; 9 10 public class HairFactory { 11 12 /** 13 * 發型對象實例的創建工廠 14 * @param key 15 * @return 16 */ 17 public static HairInterface newClass(String key){ 18 HairInterface hair = null; 19 switch(key){ 20 case "right": 21 hair = new RightHair(); 22 break; 23 case "left": 24 hair = new LeftHair(); 25 break; 26 default: 27 break; 28 29 } 30 return hair; 31 } 32 33 }
測試類:
1 /* 2 * 創 建 者: ouyangshengduo 3 * 創建時間: 2017年3月31日 4 * 文件名稱: Client.java 5 * 版權信息: 2017 Edan. All rights reserved. 6 * 文件描述: 測試類 7 */ 8 package com.oysd.model.factory; 9 10 public class Client { 11 12 public static void main(String[] args) { 13 // TODO Auto-generated method stub 14 15 HairInterface hair = HairFactory.newClass("right"); 16 17 hair.draw(); 18 19 } 20 21 }
