public
class
Student {
private
String
id
;
private
String
name
;
private
String
cardId
;
private
int
age
;
getter/setter()
。。。
}
|
public
interface
StudentDAO {
public
boolean
insertStudent(Student student);
public
boolean
deleteStudent(
int
id);
public
Student findStudent(
int
id);
}
|
public
abstract
class
DAOFactory {
// List of DAO types supported by the factory
public
static
final
int
SQLSERVER
= 1;
public
static
final
int
MYSQL
= 2;
// There will be a method for each DAO that can be
// created. The concrete factories will have to
// implement these methods.
public
abstract
StudentDAO getStudentDAO();
public
static
DAOFactory getDAOFactory(
int
whichFactory) {
switch
(whichFactory) {
case
SQLSERVER
:
return
new
SqlServerDAOFactory();
case
MYSQL
:
return
new
MySqlDAOFactory();
default
:
return
null
;
}
}
}
|
public
class
SqlServerDAOFactory
extends
DAOFactory{
public
static
final
String
DRIVER
=
"com.microsoft.sqlserver.jdbc.SQLServerDriver"
;
public
static
final
String
DBURL
=
"jdbc:sqlserver://localhost:1025; DatabaseName=tmp"
;
private
static
String
userName
=
"sa"
;
private
static
String
userPwd
=
"root"
;
public
static
Connection createConnection() {
Connection dbConn =
null
;
try
{
Class.forName(
DRIVER
);
dbConn = DriverManager.getConnection(
DBURL
,
userName
,
userPwd
);
}
catch
(ClassNotFoundException e) {
e.printStackTrace();
}
catch
(SQLException e) {
e.printStackTrace();
}
return
dbConn;
}
public
StudentDAO getStudentDAO() {
return
new
SqlServerStudentDAO(createConnection());
}
。。。。。。
}
|
public
abstract
class
StudentDAODefaultImpl
implements
StudentDAO {
private
Connection
dbConn
;
public
StudentDAODefaultImpl(Connection dbConn) {
this
.
dbConn
= dbConn;
}
public
boolean
deleteStudent(
int
id) {
Statement stmt;
try
{
stmt =
dbConn
.createStatement();
String sql =
"DELETE FROM student_table WHERE id = '"
+ id +
"'"
;
int
delete = stmt.executeUpdate(sql);
if
(delete == 1)
return
true
;
}
catch
(SQLException e) {
e.printStackTrace();
}
return
false
;
}
public
Student findStudent(
int
id) {
。。。
}
public
boolean
insertStudent(Student stu) {
。。。
}
}
|
public
class
SqlServerStudentDAO
extends
StudentDAODefaultImpl {
private
Connection
dbConn
=
SqlServer
DAOFactory.createConnection();
public
SqlServerStudentDAO(Connection dbConn) {
super
(dbConn);
}
public
Connection getDbConn() {
return
dbConn
;
}
}
|
public
class
Test {
public
static
void
main(String[] args) {
Student student =
new
Student(
"1"
,
"zj"
,
"0901"
, 27);
DAOFactory mysqlDAOFactory = DAOFactory.getDAOFactory(DAOFactory.
MYSQL
);
StudentDAO studentDAO = mysqlDAOFactory.getStudentDAO();
studentDAO.insertStudent(student);
}
}
|