设计模式总结篇系列:工厂方法模式(Factory Method)
生活随笔
收集整理的這篇文章主要介紹了
设计模式总结篇系列:工厂方法模式(Factory Method)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
工廠方法模式適合于對實現了同一接口或繼承了同一父類的一些類進行實例的創建。一般是通過定義一個工廠類,并在其方法中實現對具有上述特點的類對象的創建。
根據具體產生類對象的方法定義形式,又可以將其分為普通工廠方法模式、多個工廠方法模式和靜態工廠方法模式。
一、普通工廠方法模式:
常見的經典寫法如下(以發送郵件和短信為例):
1.定義郵件類和短信類具有的共同接口:
1 interface Sender{ 2 3 public void sender(); 4 5 }2.定義郵件類和短信類:
1 class MailSender implements Sender{ 2 3 @Override 4 public void send() { 5 System.out.println("發送郵件"); 6 } 7 8 } 1 class SmsSender implements Sender{ 2 3 @Override 4 public void send() { 5 System.out.println("發送短信"); 6 } 7 8 }3.定義工廠類:
1 class SenderFactory { 2 3 public Sender produce(String type) { 4 if (type.equals("mail")) { 5 return new MailSender(); 6 } else if (type.equals("sms")) { 7 return new SmsSender(); 8 } else { 9 return null; 10 } 11 } 12 13 }4.測試生成MailSender和SmsSender對象:
1 package com.qqyumidi; 2 3 public class FactoryMethodTest { 4 5 public static void main(String[] args) { 6 SenderFactory factory = new SenderFactory(); 7 Sender mailSender = factory.produce("mail"); 8 Sender smsSender = factory.produce("sms"); 9 } 10 11 }?
二、多個工廠方法模式:
將普通工廠模式中的工廠類中創建類的方法從依賴于參數判斷改為直接針對每種對象各自定義一個生產方法。
具體代碼如下:
1 class SenderFactory { 2 3 public Sender produceMail(){ 4 return new MailSender(); 5 } 6 7 public Sender produceSms(){ 8 return new SmsSender(); 9 } 10 11 }?
三、靜態工廠方法模式:
靜態工廠方法模式與前面兩種具體的方法定義不同在于方法被定義成靜態的,這樣可以不通過創建工廠實例就能直接獲取到目標類的對象。
1 class SenderFactory { 2 3 public static Sender produceMail(){ 4 return new MailSender(); 5 } 6 7 public static Sender produceSms(){ 8 return new SmsSender(); 9 } 10 11 }?
對于工廠方法模式,推薦使用第三種寫法。
?
---------------------------------------------------------------------------------筆者水平有限,若有錯漏,歡迎指正,如果轉載以及CV操作,請務必注明出處,謝謝! 分類: 設計模式
本文轉自Windstep博客園博客,原文鏈接:http://www.cnblogs.com/lwbqqyumidi/p/3744842.html,如需轉載請自行聯系原作者
總結
以上是生活随笔為你收集整理的设计模式总结篇系列:工厂方法模式(Factory Method)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 梦到和同事吃饭是什么意思
- 下一篇: ASP.NET MVC5+EF6+Eas