Java --- summary application of design patterns

Source: Internet
Author: User

Java --- summary application of design patterns

I wrote a small app, but the focus is not on the software. The software has many bugs and has not been modified.
This small software is only used to better describe and understand the design module.
Java programming-Package Structure
A large part of the system architecture of Java programming is embodied in the package structure.
Let's take a look at the hierarchy of my small software:

The structure is quite clear.
A typical Java application package structure:
Prefix. Application or project name. module combination. Technical implementation within the module
Note:
1. Prefix: it refers to the reverse Writing of the website domain name, removing www (such as Sun (non-JDK-level) stuff: com. sun .*).
2. The combination of modules consists of systems, subsystems, modules, and components (depending on the project size. If the project is large, it should be divided into several layers.
3. The internal technical implementation of the module is generally composed of the presentation layer, logic layer, and data layer.
For public modules or public classes that are used by many classes, you can create a package independently, named common or base, and place these public classes in it.
You can create an util or tool package for a public module or public class.
In this example, the util package.

Common design and implementation methods and basic functions of DAO
★DESIGN: from big to small
First, we break down a big problem into a series of small problems. In other words, a large system is divided into multiple small systems, and the small system is further decomposed until it is able to be controlled by itself.

★Implementation: from small to large
The component is implemented first, the test is passed, and then several components are implemented into the merging module. The test is passed, and then the expansion continues. <喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> Release + oe8g1 + 615 NDNtcREQU + 907/release/Na1vfjQ0LLp0a + horvxyKHL + release + vfjQ0LLp0a + release "" src = "http://www.bkjia.com/uploads/allimg/160409/04323MC1-1.png" title = "\"/>

★A general DAO Interface Template

★Differences between UserVO and UserQueryVO
UserVO encapsulates data records, while UserQueryVO encapsulates query conditions.

The following is a brief summary of the small software's implementation of these design patterns:
(Including hierarchical thinking, value object, factory method, Dao component, interface-Oriented Programming)

Main method class:
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();    }}

Public module type utils class:
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) {ListList = new ArrayList(); ObjectInputStream objIn = null; try {objIn = new ObjectInputStream (new FileInputStream (fileName); Object obj; // ※※※available () cannot be used to read Object streams () to determine, but should use exceptions to determine whether to read the end while (true) {obj = objIn. readObject (); list. add (obj) ;}} catch (FileNotFoundException e) {e. printStackTrace ();} catch (IOException e) {// when you read the end of the file, an exception occurs. You can determine whether the read ends. // Therefore, in this program, the normal file reading ends, not the exception we previously thought -- so no exception information is output} catch (ClassNotFoundException e) {// when reading the end of a file, an exception occurs. You can determine whether to read the end of the file. // Therefore, in this program, the normal file reading ends, not the exception we previously thought -- so no exception information is output} 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 ), if the value is true, it indicates adding instead of overwriting objOut. writeO Bject (obj);} catch (Exception e) {e. printStackTrace (); return false;} finally {if (objOut! = Null) {try {objOut. close () ;}catch (IOException e) {e. printStackTrace () ;}} return true ;}}

Value Object:
Encapsulate data records:
User:

Package cn. hncu. app. vo; import java. io. Serializable; public class User implements Serializable {// You must implement this interface !!! 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 * res Ult + 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 ;}}

Encapsulate query conditions:

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 class (data layer ):

Interface 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 (); // add, delete, and modify public boolean addUser (User user User); public boolean delete (user User ); // sometimes the parameter can also be set to: id public boolean update (User user); // query public User getByUserId (String uuid); // query a single public Collection
  
   
GetAll (); // query all public collections
   
    
GeByCondition (UserQueryVO qvo); // only writes the interface and does not apply it .... Here are the main learning methods}
   
  

Factory method 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();    }}

Implementation class 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;    }}
   
  

Logic layer:
Interface UserEbi:

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

Factory userebifacloud:

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();    }}

Implementation class 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();    }}

Presentation Layer:

UserAddPanel class:

/** 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. userebifacloud; 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 actionreceivmed (java. awt. event. actionEvent evt) {jbutton1actionreceivmed (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 jbutton1actionreceivmed (java. awt. event. actionEvent evt) {// 1 collection parameter String name = tfdName. getText (); String strAge = tfdAge. getText (); int age = Integer. parseInt (strAge); // converts it to an integer. // 2 Organization parameters // User user = new User (name, age); User user = new User (); user. setAge (age); user. setName (name); // 3 call the logic layer --- through the interface UserEbi userEbi = userebifacloud. getUserEbi (); boolean isSuccess = userEbi. addUser (user); // 4 directs to different pages if (isSuccess) {JOptionPane. showMessageDialog (this, "congratulations, added successfully! "); This. mainFrame. setContentPane (new UserListPanel (mainFrame); this. mainFrame. validate ();} else {JOptionPane. showMessageDialog (this," congratulations, adding failed! ") ;}// 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 class:

/* * 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}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.