编写一个简单的用户管理系统(工厂代理模式)

来源:互联网 发布:百度最新算法 编辑:程序博客网 时间:2024/06/11 20:17

1、编写User类-->User.java

package org.user;import java.util.Date;public class User {private int id;private String name;private String sex;private String password;private Date   birthday;public void setPassword(String passwd){this.password=passwd;}public String getPassword(){return  this.password;}public void setId(int id) {this.id = id; }public void setName(String name) {this.name = name; }public void setSex(String sex) {this.sex = sex; }public void setBirthday(Date birthday) {this.birthday = birthday; }public int getId() {return (this.id); }public String getName() {return (this.name); }public String getSex() {return (this.sex); }public Date getBirthday() {return (this.birthday); }public String toString() {String sep = System.getProperty("line.separator");StringBuffer buffer = new StringBuffer();buffer.append("id = ");buffer.append(id);buffer.append(" name = ");buffer.append(name);buffer.append(" sex = ");buffer.append(sex);buffer.append(" birthday = ");StringBuffer datebuf=new StringBuffer();datebuf.append(birthday.getYear()+1900+"-");datebuf.append(birthday.getMonth()+1+"-");datebuf.append(birthday.getDate());buffer.append(datebuf);return buffer.toString();}public boolean isEmpty(){if(this.id==0 &&this.name.isEmpty()&&this.sex.isEmpty() && this.birthday==null){return  true;}else{return false;}}}

2、定义IUser接口-->IUser.java

package org.iuser;import  org.user.User;import  java.util.List;public interface IUser {public boolean    doCreate(User user) throws  Exception;public boolean    doUpdate(User user) throws  Exception;public boolean    doDelete(int id) throws Exception;public User       doFindById(int id) throws Exception;public List<User> doFindAll(String keyWord) throws Exception;}

3、实现IUser接口 -->IUserImpl.java

package org.iuserimpl;import org.iuser.IUser;import org.user.User;import java.util.List;import java.sql.Connection;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.util.List;import java.util.ArrayList;import org.user.User;public class IUserImpl implements IUser {private Connection conn=null;public IUserImpl(Connection conn){this.conn=conn;}/** * Method doCreate * * * @param user * @throws Exception * * @return * */public boolean doCreate(User user) throws Exception {// TODO: Add your code hereboolean  flag=true;PreparedStatement ps=null;String sql="insert into user (name,password,sex,birthday) values (?,?,?,?)";try{ps=this.conn.prepareStatement(sql);ps.setString(1,user.getName());ps.setString(2,user.getPassword());ps.setString(3,user.getSex());ps.setDate(4, new java.sql.Date(user.getBirthday().getTime()));if(ps.executeUpdate()>0){flag=true;}else{flag=false;}}catch(Exception e){throw  e;}finally{if(ps!=null){try{ps.close();}catch(Exception e){throw  e;}}}return  flag;}/** * Method doUpdate * * * @param user * @throws Exception * * @return * */public boolean doUpdate(User user) throws Exception {// TODO: Add your code hereboolean flag=false;PreparedStatement pstmt=null;String sql="update user set name=?,password=?,sex=?,birthday=? where id=?";try{pstmt=this.conn.prepareStatement(sql);pstmt.setString(1,user.getName());pstmt.setString(2,user.getPassword());pstmt.setString(3,user.getSex());pstmt.setDate(4, new java.sql.Date(user.getBirthday().getTime()));pstmt.setInt(5,user.getId());if(pstmt.executeUpdate()>0){flag=true;}}catch(Exception e){throw e;}finally{if(pstmt!=null){try{pstmt.close();}catch(Exception e){throw e;}}//this.dbc.close();}return flag;}/** * Method doDelete * * * @param id * @throws Exception * * @return * */public boolean doDelete(int id) throws Exception {// TODO: Add your code hereboolean  flag=true;PreparedStatement ps=null;String sql="delete from user where id=?";try{ps=this.conn.prepareStatement(sql);ps.setInt(1,id);if(ps.executeUpdate()>0){flag=true;}else{flag=false;}}catch(Exception e){throw  e;}finally{if(ps!=null){try{ps.close();}catch(Exception e){throw  e;}}}return  flag;}/** * Method doFindById * * * @param id * @throws Exception * * @return * */public User doFindById(int id) throws Exception {// TODO: Add your code hereUser user=new User();PreparedStatement ps=null;String sql="select id,name,sex,birthday from user where id=? ";try{ps=this.conn.prepareStatement(sql);ps.setInt(1,id);ResultSet rs=ps.executeQuery();if(rs.next()){user.setId(rs.getInt(1));user.setName(rs.getString(2));user.setSex(rs.getString(3));user.setBirthday(rs.getDate(4));}rs.close();}catch(Exception e){throw  e;}finally{if(ps!=null){try{ps.close();}catch(Exception e){throw  e;}}}return user;}/** * Method doFindAll * * * @param keyWord * @throws Exception * * @return * */public List<User> doFindAll(String keyWord) throws Exception {// TODO: Add your code hereList<User> allUser=new ArrayList<User>();PreparedStatement ps=null;String sql = "SELECT id,name,sex,birthday FROM user WHERE name LIKE ? OR sex LIKE ? OR birthday LIKE ?";try{ps=this.conn.prepareStatement(sql);ps.setString(1,"%"+keyWord+"%");ps.setString(2,"%"+keyWord+"%");ps.setString(3,"%"+keyWord+"%");ResultSet rs=ps.executeQuery();while(rs.next()){User user=new User();user.setId(rs.getInt(1));user.setName(rs.getString(2));user.setSex(rs.getString(3));user.setBirthday(rs.getDate(4));allUser.add(user);}rs.close();}catch(Exception e){throw  e;}finally{if(ps!=null){try{ps.close();}catch(Exception e){throw  e;}}}return allUser;}}

4、接口的代理模式-->IUserImplPoxy.java

package org.iuserimplpoxy;import org.iuser.IUser;import org.user.User;import java.util.List;import java.sql.Connection;import org.dataconnection.DataConnection;import org.iuserimpl.IUserImpl;import org.iuser.IUser;import java.util.ArrayList;public class IUserImplPoxy implements IUser {private  Connection conn=null;private  IUser  dao=null;public IUserImplPoxy(){DataConnection dbc=new DataConnection();conn=dbc.GetConnection();dao=new IUserImpl(conn);}/** * Method doCreate * * * @param user * @throws Exception * * @return * */public boolean doCreate(User user) throws Exception {// TODO: Add your code hereboolean  flag=true;try{flag=this.dao.doCreate(user);}catch(Exception e){e.printStackTrace();}finally{if(conn!=null){try{conn.close();}catch(Exception e){e.printStackTrace();}}}return  flag;}/** * Method doUpdate * * * @param user * @throws Exception * * @return * */public boolean doUpdate(User user) throws Exception {// TODO: Add your code hereboolean  flag=true;try{flag=this.dao.doUpdate(user);}catch(Exception e){e.printStackTrace();}finally{if(conn!=null){try{conn.close();}catch(Exception e){e.printStackTrace();}}}return  flag;}/** * Method doDelete * * * @param id * @throws Exception * * @return * */public boolean doDelete(int id) throws Exception {// TODO: Add your code hereboolean  flag=true;try{flag=this.dao.doDelete(id);}catch(Exception e){e.printStackTrace();}finally{if(conn!=null){try{conn.close();}catch(Exception e){e.printStackTrace();}}}return  flag;}/** * Method doFindById * * * @param id * @throws Exception * * @return * */public User doFindById(int id) throws Exception {// TODO: Add your code hereUser user=new User();try{user=this.dao.doFindById(id);}catch(Exception e){e.printStackTrace();}finally{if(conn!=null){try{conn.close();}catch(Exception e){e.printStackTrace();}}}return  user;}/** * Method doFindAll * * * @param keyWord * @throws Exception * * @return * */public List doFindAll(String keyWord) throws Exception {// TODO: Add your code hereList<User>  alluser=new ArrayList<User>();try{alluser=this.dao.doFindAll(keyWord);}catch(Exception e){e.printStackTrace();}finally{if(conn!=null){try{conn.close();}catch(Exception e){e.printStackTrace();}}}return  alluser;}}
5、设计代理工厂factory

package org.factory;import org.iuser.IUser;import org.iuserimplpoxy.IUserImplPoxy;public  class Factory {public  static IUser getIntance(){return new IUserImplPoxy();}}
6、工具类-->InputData.java

package org.inputdata;import java.io.BufferedReader;import java.io.InputStreamReader;import java.io.IOException;import java.util.Date;import java.text.SimpleDateFormat;public class InputData {private BufferedReader buf=null;public InputData(){buf=new BufferedReader(new InputStreamReader(System.in));}public  int    getInt(String str,String err){boolean flag=true;int i=0;while(flag){String temp=this.getString(str);if(temp.matches("\\d+")){i=Integer.parseInt(temp);flag=false;}else{System.out.println(err);}}return  i;}public  String getString(String str){boolean flag=true;String  str1=null;while(flag){System.out.print(str);try{str1=buf.readLine();}catch(IOException e){e.printStackTrace();}flag=false;}return str1;}public  Date getDate(String str,String err){boolean flag=true;String  temp=null;Date    date=null;while(flag){temp=this.getString(str);if(temp.matches("\\d{4}-\\d{2}-\\d{2}")){try{date=new SimpleDateFormat("yyyy-MM-dd").parse(temp);}catch(Exception e){e.printStackTrace();}flag=false;}else{System.out.println(err);}}return date;}}

7、用户操作-->UserOperate.java

package org.useroperate;import  org.factory.Factory;import  org.user.User;import  org.inputdata.InputData;import  java.util.List;import  java.util.ArrayList;import  java.util.Iterator;public class UserOperate {public  static void insert(){InputData in=new InputData();User user=new User();user.setName(in.getString("请输入姓名:"));user.setPassword(in.getString("请输入用户密码:"));user.setSex(in.getString("请输入性别:"));user.setBirthday(in.getDate("请输入生日:","请输入格式为YYYY-MM-DD!"));try{if(Factory.getIntance().doCreate(user)){System.out.println("增加用户成功!");}else{System.out.println("增加用户失败!");}}catch(Exception e){e.printStackTrace();}}public static void update(){InputData in=new InputData();User user=new User();user.setId(in.getInt("请输入用户ID:","请输入整数!"));user.setName(in.getString("请输入姓名:"));;user.setPassword(in.getString("请输入密码:"));user.setSex(in.getString("请输入性别:"));user.setBirthday(in.getDate("请输入生日:","请输入格式为YYYY-MM-DD!"));try{Factory.getIntance().doUpdate(user);}catch(Exception e){e.printStackTrace();}}public static void delete(){InputData in=new InputData();int id=0;id=in.getInt("请输入用户ID:","请输入整数!");try{if(Factory.getIntance().doDelete(id)){System.out.println("删除用户成功!");}else{System.out.println("删除用户失败!");}}catch(Exception e){e.printStackTrace();}}public static  void findById(){User user=new User();InputData in=new InputData();int id=0;id=in.getInt("请输入用户ID:","请输入整数!");try{user=Factory.getIntance().doFindById(id);}catch(Exception e){e.printStackTrace();}if(!user.isEmpty()){System.out.println(user);}else{System.out.println("无用户!");}}public static void findAll(){List<User> alluser=new ArrayList<User>();InputData in=new InputData();String keyWord=null;keyWord=in.getString("请输入关键字:");try{alluser=Factory.getIntance().doFindAll(keyWord);}catch(Exception e){e.printStackTrace();}if(alluser!=null){Iterator it=alluser.iterator();while(it.hasNext()){System.out.println(it.next());}}else{System.out.println("无用户!");}}}

8、连接数据库

package org.dataconnection;import java.sql.DriverManager;import java.sql.SQLException;import java.sql.Connection;public class DataConnection {private static final String DRIVERNAME="org.gjt.mm.mysql.Driver";private static final String DATABASEURL="jdbc:mysql://localhost:3306/useManager";private static final String DATANAME="root";private static final String DATAPASS="root";public DataConnection() {try{Class.forName(DRIVERNAME);}catch(ClassNotFoundException e){e.printStackTrace();}}public Connection GetConnection(){Connection conn=null;try{ conn=DriverManager.getConnection(DATABASEURL,DATANAME,DATAPASS);}catch(SQLException e){e.printStackTrace();}return conn;}}

9、用户界面

package org.menu;import org.useroperate.UserOperate;import org.inputdata.InputData;public class Menu {public Menu(){while(true){this.show();}}private void  show(){System.out.println("=======================用户管理系统==================================");System.out.println("\t\t1.增加用户");System.out.println("\t\t2.更改用户");System.out.println("\t\t3.删除用户");System.out.println("\t\t4.查找单个用户");System.out.println("\t\t5.查找所用用户");System.out.println("\t\t6.退出系统");System.out.println("=======================用户管理系统==================================");int ch=0;InputData in=new InputData();ch=in.getInt("请选择菜单:","请输入整数!");switch(ch){case 1:UserOperate.insert();break;case 2:UserOperate.update();break;case 3:UserOperate.delete();break;case 4:UserOperate.findById();break;case 5:UserOperate.findAll();break;default :System.exit(0);}}}

10、程序入口

package org.mysql;import java.sql.Connection;import java.sql.Statement;import java.sql.ResultSet;import java.sql.DriverManager;import java.sql.SQLException;import java.util.Date;import org.user.User;import org.inputdata.InputData;import org.factory.Factory;import org.useroperate.UserOperate;import org.menu.Menu;import org.dataconnection.DataConnection;public class MySQL{public static void main(String [] args){Menu m=new Menu();}}


原创粉丝点击