Java---設計模式匯總應用

來源:互聯網
上載者:User

Java---設計模式匯總應用

寫了一個app小軟體,重點不在於軟體,軟體bug挺多,也沒去修改。
這個小軟體只是為了更好的說明和瞭解設計模組而做的。
Java 程式設計–包結構
Java程式設計的系統體繫結構很大一部分都體現在包結構上
大家看看我的這個小軟體的分層:

結構還是挺清楚的。
一種典型的Java應用程式的包結構:
首碼.應用或項目的名稱.模組組合.模組內部的技術實現
說明:
1、首碼:是網站網域名稱的倒寫,去掉www(如,Sun公司(非JDK層級)的東西:com.sun.* )。
2、其中模組組合又由系統、子系統、模組、組件等構成(具體情況根據項目的大小而定,如果項目很大,那麼就多分幾層。
3、模組內部的技術實現一般由:表現層、邏輯層、資料層等構成。
對於許多類都要使用的公用模組或公用類,可以再獨立建立一個包,取名common或base,把這些公用類都放在其中。
對於功能上的公用模組或公用類可建立util或tool包,放入其中。
如本例的util包。

設計與實現的常用方式、DAO的準系統
★ 設計的時候:從大到小
先把一個大問題分解成一系列的小問題。或者說是把一個大系統分解成多個小系統,小系統再繼續進行往下分解,直到分解到自己能夠掌控時,再進行動手實現。

★ 實現的時候:從小到大
先實現組件,進行測試通過了,再把幾個組件實現合成模組,進行測試通過,然後繼續往上擴大。<喎?http://www.bkjia.com/kf/ware/vc/" target="_blank" class="keylink">vcD4NCjxwPjxzdHJvbmc+oe8g1+615NDNtcREQU+907/azaizo77f09C1xLmmxNw8L3N0cm9uZz48YnIgLz4NCtDC1Pa5psTcoaLQ3rjEuabE3KGiyb6z/bmmxNyhorC01dXW99KqtcS8/Na1vfjQ0LLp0a+horvxyKHL+dPQ1rW1xLmmxNyhorC01dXM9bz+vfjQ0LLp0a+1xLmmxNyhozxiciAvPg0KPGltZyBhbHQ9"" src="http://www.bkjia.com/uploads/allimg/160409/04323MC1-1.png" title="\" />

★ 一個通用DAO介面模板

★ UserVO 和 UserQueryVO的區別
UserVO封裝資料記錄,而UserQueryVO用於封裝查詢條件。

下面的為那個小軟體實現這些設計模式的簡單匯總:
(含分層思想,值對象,Factory 方法,Dao組件,面向介面編程)

main方法類:
UserClient :

package cn.hncu.app;import cn.hncu.app.ui.UserAddPanel;public class UserClient extends javax.swing.JFrame {    public UserClient(){        super("chx");        this.setDefaultCloseOperation(EXIT_ON_CLOSE);        this.setBounds(100, 100, 800, 600);        this.setContentPane(new UserAddPanel(this));        this.setVisible(true);    }    public static void main(String[] args) {        new UserClient();    }}

公用模組類 utils類:
FileIO :

package cn.hncu.app.utils;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.ObjectInputStream;import java.io.ObjectOutputStream;import java.util.ArrayList;import java.util.List;public class FileIO {    public static Object[] read(String fileName){        List list = new ArrayList();        ObjectInputStream objIn=null;        try {            objIn = new ObjectInputStream(new FileInputStream(fileName));            Object obj;            //※※物件流程的讀不能用available()來判斷,而應該用異常來確定是否讀到結束            while(true){                obj=objIn.readObject();                list.add(obj);              }        } catch (FileNotFoundException e) {            e.printStackTrace();        } catch (IOException e) {            //讀到檔案末尾,就是出異常,通過這來判斷是否讀到結束。            //因此,本程式中,這裡是正常的檔案讀取結束,不是我們之前認為的出異常--所以不輸出異常資訊        } catch (ClassNotFoundException e) {            //讀到檔案末尾,就是出異常,通過這來判斷是否讀到結束。            //因此,本程式中,這裡是正常的檔案讀取結束,不是我們之前認為的出異常--所以不輸出異常資訊        }finally{            if(objIn!=null){                try {                    objIn.close();                } catch (IOException e) {                    e.printStackTrace();                }            }        }        Object[] objs = list.toArray();        if(objs==null){            objs=new Object[0];        }        return objs;    }    public static boolean write(String fileName,Object obj){        ObjectOutputStream objOut =null;        try {            objOut=new ObjectOutputStream(new FileOutputStream(fileName,true));            //new FileOutputStream(fileName,true),有true的存在代表是添加而不是覆蓋            objOut.writeObject(obj);        } catch (Exception e) {            e.printStackTrace();            return false;        }finally{            if(objOut!=null){                try {                    objOut.close();                } catch (IOException e) {                    e.printStackTrace();                }            }        }        return true;    }}

值對象:
封裝資料記錄:
User:

package cn.hncu.app.vo;import java.io.Serializable;public class User implements Serializable{//一定要實現這個介面啊!!!    private String name;    private int age;    public User(String name, int age) {        this.name = name;        this.age = age;    }    public User() {    }    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public int getAge() {        return age;    }    public void setAge(int age) {        this.age = age;    }    @Override    public int hashCode() {        final int prime = 31;        int result = 1;        result = prime * result + age;        result = prime * result + ((name == null) ? 0 : name.hashCode());        return result;    }    @Override    public boolean equals(Object obj) {        if (this == obj)            return true;        if (obj == null)            return false;        if (getClass() != obj.getClass())            return false;        User other = (User) obj;        if (age != other.age)            return false;        if (name == null) {            if (other.name != null)                return false;        } else if (!name.equals(other.name))            return false;        return true;    }    @Override    public String toString() {        return  name + "," + age;    }}

封裝查詢條件:

UserQueryVO :

package cn.hncu.app.vo;public class UserQueryVO extends User{    private String age2;//年齡段尋找    public String getAge2() {        return age2;    }    public void setAge2(String age2) {        this.age2 = age2;    }}

Dao類(資料層):

介面UserDAO :

package cn.hncu.app.dao.dao;import java.util.Collection;import cn.hncu.app.vo.User;import cn.hncu.app.vo.UserQueryVO;public interface UserDAO {    public Object[] getAllUsers();    //增刪改    public boolean addUser(User user);    public boolean delete(User user);//有時參數也可以用:id    public boolean update(User user);    //3個查詢    public User getByUserId(String uuid);//查單個    public Collection getAll();//查全    public Collection geByCondition(UserQueryVO qvo);    //唯寫了介面,並沒有具體去應用。。。。這裡主要學方法}

Factory 方法UserDaoFactory :

package cn.hncu.app.dao.factory;import cn.hncu.app.dao.dao.UserDAO;import cn.hncu.app.dao.impl.UserDaoFileIO;public class UserDaoFactory {    public static UserDAO getUserDAO(){        return new UserDaoFileIO();    }}

實作類別 UserDaoFileIO :

package cn.hncu.app.dao.impl;import java.util.Collection;import cn.hncu.app.dao.dao.UserDAO;import cn.hncu.app.utils.FileIO;import cn.hncu.app.vo.User;import cn.hncu.app.vo.UserQueryVO;public class UserDaoFileIO implements UserDAO{    private static final String FILE_NAME = "user.txt";    @Override    public Object[] getAllUsers() {        return FileIO.read(FILE_NAME);    }    @Override    public boolean addUser(User user) {        return FileIO.write(FILE_NAME, user);    }    @Override    public boolean delete(User user) {        return false;    }    @Override    public boolean update(User user) {        return false;    }    @Override    public User getByUserId(String uuid) {        return null;    }    @Override    public Collection getAll() {        return null;    }    @Override    public Collection geByCondition(UserQueryVO qvo) {        return null;    }}

邏輯層:
介面UserEbi :

package cn.hncu.app.business.ebi;import cn.hncu.app.vo.User;public interface UserEbi {    public boolean addUser(User user);    public Object[] getAllUser();}

工廠類UserEbiFactory :

package cn.hncu.app.business.factory;import cn.hncu.app.business.ebi.UserEbi;import cn.hncu.app.business.impl.UserEbo;public class UserEbiFactory {    public static UserEbi getUserEbi(){        return new UserEbo();    }}

實作類別UserEbo :

package cn.hncu.app.business.impl;import cn.hncu.app.business.ebi.UserEbi;import cn.hncu.app.dao.dao.UserDAO;import cn.hncu.app.dao.factory.UserDaoFactory;import cn.hncu.app.vo.User;public class UserEbo implements UserEbi{    @Override    public boolean addUser(User user) {        UserDAO userDao = UserDaoFactory.getUserDAO();        return userDao.addUser(user);    }    @Override    public Object[] getAllUser() {        UserDAO userDao = UserDaoFactory.getUserDAO();        return userDao.getAllUsers();    }}

表現層:

UserAddPanel 類:

/* * UserAddPanel.java * * Created on __DATE__, __TIME__ */package cn.hncu.app.ui;import javax.swing.JFrame;import javax.swing.JOptionPane;import cn.hncu.app.business.ebi.UserEbi;import cn.hncu.app.business.factory.UserEbiFactory;import cn.hncu.app.vo.User;/** * * @author  __USER__ */public class UserAddPanel extends javax.swing.JPanel {    private JFrame mainFrame = null;    /** Creates new form UserAddPanel */    public UserAddPanel(JFrame mainFrame) {        this.mainFrame = mainFrame;        initComponents();    }    /** This method is called from within the constructor to     * initialize the form.     * WARNING: Do NOT modify this code. The content of this method is     * always regenerated by the Form Editor.     */    //GEN-BEGIN:initComponents    //     private void initComponents() {        jLabel1 = new javax.swing.JLabel();        jLabel2 = new javax.swing.JLabel();        jButton1 = new javax.swing.JButton();        tfdAge = new javax.swing.JTextField();        tfdName = new javax.swing.JTextField();        setMinimumSize(new java.awt.Dimension(800, 600));        setLayout(null);        jLabel1.setText("\u5e74\u9f84\uff1a");        add(jLabel1);        jLabel1.setBounds(170, 200, 50, 40);        jLabel2.setText("\u59d3\u540d\uff1a");        add(jLabel2);        jLabel2.setBounds(170, 120, 50, 40);        jButton1.setText("\u6dfb\u52a0");        jButton1.addActionListener(new java.awt.event.ActionListener() {            public void actionPerformed(java.awt.event.ActionEvent evt) {                jButton1ActionPerformed(evt);            }        });        add(jButton1);        jButton1.setBounds(240, 330, 170, 60);        add(tfdAge);        tfdAge.setBounds(210, 210, 170, 30);        add(tfdName);        tfdName.setBounds(210, 130, 170, 30);    }//     //GEN-END:initComponents    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {        //1收集參數         String name = tfdName.getText();        String strAge = tfdAge.getText();        int age = Integer.parseInt(strAge);//簡單的轉換成一個整型數了。        //2組織參數        //User user = new User(name, age);        User user = new User();        user.setAge(age);        user.setName(name);        //3調用邏輯層---通過介面        UserEbi userEbi = UserEbiFactory.getUserEbi();        boolean isSuccess=userEbi.addUser(user);        //4導向不同頁面        if(isSuccess){            JOptionPane.showMessageDialog(this, "恭喜,添加成功!");            this.mainFrame.setContentPane(new UserListPanel(mainFrame));            this.mainFrame.validate();        }else{            JOptionPane.showMessageDialog(this, "祝賀,添加失敗!");        }    }    //GEN-BEGIN:variables    // Variables declaration - do not modify    private javax.swing.JButton jButton1;    private javax.swing.JLabel jLabel1;    private javax.swing.JLabel jLabel2;    private javax.swing.JTextField tfdAge;    private javax.swing.JTextField tfdName;    // End of variables declaration//GEN-END:variables}

UserListPanel 類:

/* * UserListPanel.java * * Created on __DATE__, __TIME__ */package cn.hncu.app.ui;import javax.swing.JFrame;import cn.hncu.app.business.ebi.UserEbi;import cn.hncu.app.business.factory.UserEbiFactory;/** * * @author  __USER__ */public class UserListPanel extends javax.swing.JPanel {    private JFrame mainFrame = null;    /** Creates new form UserListPanel */    public UserListPanel(JFrame mainFrame) {        this.mainFrame = mainFrame;        initComponents();        myInitDatas();    }    private void myInitDatas() {        UserEbi userEbi = UserEbiFactory.getUserEbi();        Object[] objs = userEbi.getAllUser();        this.listUsers.setListData(objs);    }    /** This method is called from within the constructor to     * initialize the form.     * WARNING: Do NOT modify this code. The content of this method is     * always regenerated by the Form Editor.     */    //GEN-BEGIN:initComponents    //     private void initComponents() {        jScrollPane1 = new javax.swing.JScrollPane();        listUsers = new javax.swing.JList();        jLabel1 = new javax.swing.JLabel();        setMinimumSize(new java.awt.Dimension(800, 600));        setLayout(null);        listUsers.setModel(new javax.swing.AbstractListModel() {            String[] strings = { "" };            public int getSize() {                return strings.length;            }            public Object getElementAt(int i) {                return strings[i];            }        });        jScrollPane1.setViewportView(listUsers);        add(jScrollPane1);        jScrollPane1.setBounds(170, 170, 410, 210);        jLabel1.setText("\u4fe1\u606f");        add(jLabel1);        jLabel1.setBounds(350, 90, 70, 50);    }//     //GEN-END:initComponents    //GEN-BEGIN:variables    // Variables declaration - do not modify    private javax.swing.JLabel jLabel1;    private javax.swing.JScrollPane jScrollPane1;    private javax.swing.JList listUsers;    // End of variables declaration//GEN-END:variables}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.