日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > asp.net >内容正文

asp.net

(设计模式)简单工厂模式之通过配置文件动态创建实现类

發布時間:2024/7/5 asp.net 27 豆豆
生活随笔 收集整理的這篇文章主要介紹了 (设计模式)简单工厂模式之通过配置文件动态创建实现类 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

通常我們在使用簡單工廠模式的時候會由創建方法create通過傳入的參數來判斷要實例化哪個對象,就像下面這樣:

public static class ImageSelectFactory {public static IImageSelect createIImageSelect(ImageSelectClientMode mode) {IImageSelect imageSelect = null;if (mode == ImageSelectClientMode.COLLECTION_IMAGE) {imageSelect = new CollectionImage();} else if (mode == ImageSelectClientMode.LOCAL_PHOTO) {imageSelect = new LocalPhoto();} else if (mode == ImageSelectClientMode.WORKS_IMAGE) {imageSelect = new WorksImage();} else if (mode == ImageSelectClientMode.TAKE_PHOTO) {imageSelect = new TakePhoto();} else if (mode == ImageSelectClientMode.SUPER_IMAGE_LIB) {imageSelect = new SuperImageLib();}return imageSelect;}}這里面定義了5個IImageSelect接口的子類,通過定義好的泛型ImageSelectClientMode來決定實例化哪個子類,現在遇到這么一個問題,如果添加到第6個子類的話,那就必須要更改ImageSelectFactory類以及枚舉ImageSelectClientMode,可能你會說“改一下又何妨?”,雖不說影響不影響什么開閉設計原則,但是有個情況你可成想到,你這個類要打包發布給別人用呢?別人在沒有源碼的情況下如何擴展呢?這里就需要我們動態的通過配置文件來加載實現類了。

實現的基本思路為:通過讀取本地的.properties文件來獲取我們需要實例化的類,然后通過反射來生成對象,這樣當你把發布出去的時候,使用者只用更改配置文件就可以讓工廠去實例化自己后來才寫的實現類,我們看看實現方式:

ImageSelectClient.properties: COLLECTION_IMAGE=com.kongfuzi.student.support.bitmap.select.CollectionImage LOCAL_PHOTO=com.kongfuzi.student.support.bitmap.select.LocalPhoto WORKS_IMAGE=com.kongfuzi.student.support.bitmap.select.WorksImage TAKE_PHOTO=com.kongfuzi.student.support.bitmap.select.TakePhoto SUPER_IMAGE_LIB=com.kongfuzi.student.support.bitmap.select.SuperImageLib


public static class ImageSelectFactory {public static IImageSelect createIImageSelect(String type) {IImageSelect mIImageSelect;//實例化Properties對象,用于讀取.propertiesProperties properties = new Properties();InputStream is = null;try {is = ImageSelectClient.class.getResourceAsStream("ImageSelectClient.properties");//裝載ImageSelectClient.properties文件properties.load(is);} catch (Exception e) {e.printStackTrace();} finally {try {is.close();} catch (IOException e) {e.printStackTrace();}}try {//根據key獲取value,value即為將要實例化的類Class<?> aClass = Class.forName(properties.getProperty(type));//使用反射進行實例化mIImageSelect = (IImageSelect) aClass.newInstance();} catch (ClassNotFoundException e) {e.printStackTrace();} catch (InstantiationException e) {e.printStackTrace();} catch (IllegalAccessException e) {e.printStackTrace();}return mIImageSelect;}}
這樣,我們就可以隨便實現子類,然后在.properties文件中添加對應的包路徑,然后通過ImageSelectFactory就可以進行實例化了。



總結

以上是生活随笔為你收集整理的(设计模式)简单工厂模式之通过配置文件动态创建实现类的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。