標籤:ret air 測試 class new print style rate auto
時間緊迫,關於原廠模式的內容有點多,要講的話大致分為簡單工廠模型,Factory 方法模型,抽象工廠模型
這裡 ,我就大概講一下簡單工廠模型,也是我們實際開發中用的相對比較多的
第一步,先建立工廠介面,也就是規定這個工廠是幹嘛的:
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 @Override16 public void draw() {17 // TODO Auto-generated method stub18 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 @Override17 public void draw() {18 // TODO Auto-generated method stub19 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 key15 * @return16 */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 stub14 15 HairInterface hair = HairFactory.newClass("right");16 17 hair.draw();18 19 }20 21 }
Android設計模式之原廠模式