編寫一個簡單的用戶管理系統(工廠代理模式)

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 here
		boolean  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 here
			boolean 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 here
		boolean  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 here
		User 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 here
		List<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 here
		boolean  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 here
		boolean  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 here
		boolean  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 here
		User 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 here
		List<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();
	}
}


發佈了39 篇原創文章 · 獲贊 15 · 訪問量 7萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章