效果
設計思路
需求分析
圖片瀏覽,上/下一張,放大縮小等基本功能。可以繼續拓展的功能:縮略圖、旋轉,畫筆修改等。此外,縮放實現較為簡單,所以會出現失真。設計此類軟件功能可參考ACDSee或irfanview等看圖軟件。
知識點
1.文件過濾、文件IO:FileFilter
2.文件對話框:JFileChooser(添加文件過濾功能)
3.瀏覽器主界面:JToolBar/JMenuBar/JScrollPane
4.響應事件:ActionListener/AbstractAction
5.展示圖片:ImageIcon
設計模式
1.單例:業務處理類並不是無狀態的Java對象,而是保存着瀏覽目錄、縮放比例等信息。
具體代碼:
public static ViewerService getInstance() { if (null == service) { service = new ViewerService(); } return service; }
2.反射:通過反射創建實例,避免if...else if.....else...,增強程序的可拓展性。
具體代碼:
1 private Action getAction(String actionName) { 2 try { 3 if (this.action == null) { 4 Action action = (Action) Class.forName("crazyit.action." + 5 actionName).newInstance(); 6 this.action = action; 7 } 8 return this.action; 9 } catch (Exception e) { 10 return null; 11 } 12 }
總結
在實踐中深入學習,重要的是在實戰過程中仔細研究文檔、積累經驗,寫出性能(算法)優良、設計(模式)合理的程序。
源代碼
https://github.com/zhaoyu1995/CrazyJava/tree/master/ImageViewer