應用場景:在java程序中,經常需要把數據持久化,也需要獲取持久化的數據,但是在進行數據持久化的過程中面臨諸多問題(如:數據源不同、存儲類型不同、供應商不同、訪問方式不同等等),請問如何能以統一的接口進行數據持久化的操作?
其實這個我沒學號(≧ ﹏ ≦)。我的理解就是一個產品面向的用戶不是單一的,所以我們要兼容許多情況如前面提到的數據源不同、存儲類型不同、供應商不同、訪問方式不同等等。
★ 解決方案
dao的理解:
1、dao其實是利用組合工廠模式來解決問題的,并沒有帶來新的功能,所以學的其實就是個思路。
2、dao理論上是沒有層數限制的
3、dao的各層理論上是沒有先后的。
項目種文件樣子:
一些代碼實現
接口
1
2
3
|
public interface depdao { public void create(string userid,string name); } |
工廠方法(多個選擇實現)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
public class f1factory { private f1factory(){ } public static depdao getdepdao(){ //根據用戶在配置文件中指定的類型來選擇具體的某個實現類 //type:類似我們學號指定的信息: 14+ 06+ 601+ 01 // 本例如: 1(type1機器類型)+ 2(type2存儲類型)+ 2(type3供應商) + 1(type4訪問方式) int type1= 1 ; //第1層工廠的選擇類型,按理應該從用戶的配置信息中獲取,這里直接模擬了 if (type1== 1 ){ return f2afactory.getdepdao(); } else if (type1== 2 ){ return f2bfactory.getdepdao(); } return null ; } } |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
public class f2afactory { private f2afactory(){ } public static depdao getdepdao(){ int type2= 2 ; //第2層工廠的選擇類型,按理應該從用戶的配置信息中獲取,這里直接模擬了 if (type2== 1 ){ // return f3a_odb_factory.getdepdao(); } else if (type2== 2 ){ return f3_a_rdb_factory.getdepdao(); } else if (type2== 3 ){ //return f3_a_xml_factory.getdepdao(); } else if (type2== 4 ){ //return f3_a_filefactory.getdepdao(); } return null ; } } |
還有幾個工廠方法類似就不貼出來了
實現類
1
2
3
4
5
6
|
public class depejb_impl implements depdao{ @override public void create(string userid, string name) { system.out.println( "利用jpa_impl向數據庫寫入:" +userid+ "," +name); } } |
如有疑問請留言或者到本站社區交流討論,感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
原文鏈接:http://blog.csdn.net/weixin_37720904/article/details/60866171