定義:定義一個用於建立產品對象的方法,由該工廠類根據傳入的參數,動態決定應該建立哪個產品類(這些產品類繼承自一個父類或接口)的實例。編程
類型:建立類模式設計模式
public interface SmsService { void sendSms(); } public class MontnetsSmsService implements SmsService { @Override public void sendSms() { System.out.println("經過夢網發送!"); } } public class EtonenetSmsService implements SmsService { @Override public void sendSms() { System.out.println("經過移通發送!"); } } public class SmsServiceFactory { public static SmsService getSmsService(int providerId) { SmsService ss; switch (providerId) { case 0: ss = new MontnetsSmsService(); break; case 1: ss = new EtonenetSmsService(); break; default: ss = new EtonenetSmsService(); } return ss; } public static void main(String[] args) { SmsService ss = SmsServiceFactory.getSmsService(0); //發送短信 ss.sendSms(); } }
定義:定義一個用於建立產品對象的接口,由子類決定實例化哪個類,工廠方法使一個類的實例化延遲到其子類。ide
類型:建立類模式spa
類圖:.net
工廠方法模式代碼:設計
public interface SmsService { void sendSms(); } //工廠接口 public interface SmsServiceFactory { SmsService getSmsService(int providerId); } public class MontnetsSmsService implements SmsService { @Override public void sendSms() { System.out.println("經過夢網發送!"); } } public class EtonenetSmsService implements SmsService { @Override public void sendSms() { System.out.println("經過移通發送!"); } } /** * 工廠實現類 */ public class SmsServiceFactoryImpl implements SmsServiceFactory{ @Override public SmsService getSmsService(int providerId) { SmsService ss; switch (providerId) { case 0: ss = new MontnetsSmsService(); break; case 1: ss = new EtonenetSmsService(); break; default: ss = new EtonenetSmsService(); } return ss; } public static void main(String[] args) { //向上轉型爲工程接口 SmsServiceFactory ssf = new SmsServiceFactoryImpl(); SmsService ss = ssf.getSmsService(0); //發送短信 ss.sendSms(); } }
工廠方法模式:code
經過工廠方法模式的類圖能夠看到,工廠方法模式有四個要素:對象
上文提到的簡單工廠模式跟工廠方法模式極爲類似,區別是:簡單工廠只有三個要素,他沒有工廠接口,而且獲得產品的方法通常是靜態的(紅色註釋部分)。由於沒有工廠接口,因此在工廠實現的擴展性方面稍弱,能夠算所工廠方法模式的簡化版。blog
如寫的很差,歡迎拍磚!繼承
PS:
http://blog.csdn.net/zhengzhb/article/details/7359385