生活随笔
收集整理的這篇文章主要介紹了
《设计模式系列》---工厂方法
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
2019獨(dú)角獸企業(yè)重金招聘Python工程師標(biāo)準(zhǔn)>>>
?簡(jiǎn)單工廠vs工廠方法
?簡(jiǎn)單工廠模式的最大優(yōu)點(diǎn)在于工廠類中包含了必要的判斷邏輯,根據(jù)客戶端的選擇條件動(dòng)態(tài)實(shí)例化相關(guān)的類,對(duì)于客戶端來(lái)說(shuō),去除了與具體產(chǎn)品的依賴。
? 工廠方法模式,定義一個(gè)用于創(chuàng)建對(duì)象的接口,讓子類決定實(shí)例化那個(gè)類,工廠方法使一個(gè)類的實(shí)例化延遲到其子類。工廠方法模式實(shí)現(xiàn)時(shí),客戶端決定實(shí)例化哪一個(gè)工廠來(lái)實(shí)現(xiàn)運(yùn)算類,選擇判斷的問(wèn)題還是存在的,也就是說(shuō),工廠方法把簡(jiǎn)單工廠的內(nèi)部邏輯判斷移到了客戶端代碼來(lái)進(jìn)行。你要想加功能,本來(lái)是改工廠類的,現(xiàn)在是修改客戶端。
/***?@author?stefanie?zhao*?@date?2014-8-15?下午01:54:36*/
public?interface?IFactory?{Leifeng?createLeiFeng();
} /***?@author?stefanie?zhao*?@date?2014-8-15?下午01:52:41*/
public?class?Leifeng?{public?void?Sweep()?{System.out.println("掃地");}public?void?Wash()?{System.out.println("洗衣");}
} /***?@author?stefanie?zhao*?@date?2014-8-15?下午01:53:48*/
public?class?Undergraduate?extends?Leifeng?{} /***?@author?stefanie?zhao*?@date?2014-8-15?下午01:55:25*/
public?class?UndergraduateFactory?implements?IFactory?{/**?(non-Javadoc)*?*?@see?us.echo.pattern.factory.IFactory#createLeiFeng()*/@Overridepublic?Leifeng?createLeiFeng()?{return?new?Undergraduate();}} /***?@author?stefanie?zhao*?@date?2014-8-15?下午01:53:48*/
public?class?Volunteer?extends?Leifeng?{} /***?@author?stefanie?zhao*?@date?2014-8-15?下午01:55:25*/
public?class?VolunteerFactory?implements?IFactory?{/**?(non-Javadoc)*?*?@see?us.echo.pattern.factory.IFactory#createLeiFeng()*/@Overridepublic?Leifeng?createLeiFeng()?{return?new?Volunteer();}} public?class?Main?{/***?@Description:?TODO*?@param?@param?args*?@return?void*?@throws*/public?static?void?main(String[]?args)?{//?TODO?Auto-generated?method?stubIFactory?factory?=?new?UndergraduateFactory();Leifeng?lf?=?factory.createLeiFeng();lf.Sweep();lf.Wash();}}
轉(zhuǎn)載于:https://my.oschina.net/stefanzhlg/blog/308126
總結(jié)
以上是生活随笔為你收集整理的《设计模式系列》---工厂方法的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。