设计模式之【工厂模式】,创建对象原来有这么多玩法

编程入门 行业动态 更新时间:2024-10-23 11:24:12

设计<a href=https://www.elefans.com/category/jswz/34/1771241.html style=模式之【工厂模式】,创建对象原来有这么多玩法"/>

设计模式之【工厂模式】,创建对象原来有这么多玩法

文章目录

  • 一、什么是工厂模式
    • 1、工厂模式的意义
    • 2、什么时候应该用工厂模式
  • 二、简单工厂模式
    • 1、实例
      • (1)使用简单工厂进行优化
      • (2)静态工厂
      • (3)使用map来去除if
      • (4)使用反射
      • (5)使用配置文件
  • 三、工厂方法模式
    • 1、实例
    • 2、什么时候该用工厂方法模式,而非简单工厂模式
  • 四、抽象工厂模式
    • 1、实例
  • 六、源码分析
    • 1、JDK-Collection.iterator方法
    • 2、Calendar
    • 3、slf4j
    • 4、其他
  • 七、使用工厂模式实现数据库连接池
    • 1、Pool
    • 2、DBConnectionPool
    • 3、配置文件
    • 4、ConManager
    • 5、DataBaseCmd

全网最全最细的【设计模式】总目录,收藏起来慢慢啃,看完不懂砍我

一、什么是工厂模式

一般情况下,工厂模式分为三种更加细分的类型:简单工厂、工厂方法和抽象工厂。不过,在 GoF 的《设计模式》一书中,它将简单工厂模式看作是工厂方法模式的一种特例,所以工厂模式只被分成了工厂方法和抽象工厂两类。

在这三种细分的工厂模式中,简单工厂、工厂方法原理比较简单,在实际的项目中也比较常用。而抽象工厂的原理稍微复杂点,在实际的项目中相对也不常用。

1、工厂模式的意义

工厂模式的意义就是,将实例化对象的代码提取出来,放到一个类中统一管理和维护,达到和主项目的依赖关系的解耦,从而提高项目的扩展和维护性。

  • 创建对象实例时,不要直接new类,而是把这个new类的动作放在一个工厂的方法中,并返回。
  • 不要让类继承具体类,而是继承抽象类或者是实现接口
  • 不要覆盖基类中已经实现的方法。

2、什么时候应该用工厂模式

当创建逻辑比较复杂,是一个“大工程”的时候,我们就考虑使用工厂模式,封装对象的创建过程,将对象的创建和使用相分离。

当每个对象的创建逻辑都比较简单的时候(用了大量if-else),我推荐使用简单工厂模式,将多个对象的创建逻辑放到一个工厂类中。当每个对象的创建逻辑都比较复杂的时候(组合其他对象做初始化工作),为了避免设计一个过于庞大的简单工厂类,我推荐使用工厂方法模式,将创建逻辑拆分得更细,每个对象的创建逻辑独立到各自的工厂类中。

但是,也应该避免遇到new就工厂模式的情况,按照需要进行使用工厂模式,但是不能滥用。

二、简单工厂模式

简单工厂模式(Simple Factory Pattern)是指由一个工厂对象决定创建出哪一种产品类的实例,但它不属于GOF23种设计模式。简单工厂适用于工厂类负责创建的对象较少的场景,且客户端只需要传入工厂类的参数,对于如何创建对象的逻辑不需要关心。

1、实例

我们以学校开设的课程为例,有Java课程、Python课程、大数据课程等等。

public interface ICourse {/*** 录制视频*/void record();
}public class JavaCourse implements ICourse {public void record() {System.out.println("创建Java课程");}
}public class PythonCourse implements ICourse {public void record() {System.out.println("创建Python课程");}
}

客户端创建课程可能会这样实现:

ICourse course = new JavaCourse();
course.record();

这样一来,每创建一门课程都需要指向一个子类的引用,如果业务扩展,客户端的依赖会越来越臃肿。
此时我们需要想办法将这种依赖减弱,把创建细节隐藏。
虽然我们目前的代码中创建对象的逻辑并不复杂,但是从代码设计角度来讲并不易于扩展。

接下来我们使用简单工厂模式对代码进行优化。

(1)使用简单工厂进行优化

我们抽象出一个创建工厂,使用工厂进行对象的创建:

public class CourseFactory {public ICourse create(String name){if("java".equals(name)){return new JavaCourse();}else if("python".equals(name)){return new PythonCourse();}else {return null;}}
}

此时客户端这样调用即可:

ICourseFactory factory = new ICourseFactory();
ICourse course = factory.create("java");
course.record();

我们的客户端,只需要依赖于对象的创建工厂即可,不会有其他额外的依赖了。

(2)静态工厂

我们将工厂中创建的方法设为静态方法,使用起来更加的方便:

public class CourseFactory {public static ICourse create(String name){if("java".equals(name)){return new JavaCourse();}else if("python".equals(name)){return new PythonCourse();}else {return null;}}
}

此时客户端这样调用即可:

ICourse course = CourseFactory.create("java");
course.record();

(3)使用map来去除if

这种方式使用map的方式去除了繁琐的if,使代码结构看起来更加清晰。

public class CourseFactory {private static final Map<String, ICourse> courses = new HashMap<>();static {courses.put("java", new JavaCourse());courses.put("python", new PythonCourse());}public static ICourse create(String name) {return courses.get(name);}
}

(4)使用反射

public class CourseFactory {public static ICourse create(Class<? extends ICourse> clazz){try {if (null != clazz) {return clazz.newInstance();}}catch (Exception e){e.printStackTrace();}return null;}
}

此时客户端:

ICourse course = CourseFactory .create(JavaCourse.class);
course.record();

这种方式将对象的创建使用反射来实现。

(5)使用配置文件

我们定义一个配置文件:

java=com.demo.JavaCourse
python=com.demo.PythonCourse

将对象的初始化过程放在配置文件里,更加灵活。

public class CourseFactory {private static final Map<String, ICourse> courses = new HashMap<>();static {Properties p = new Properties();InputStream is =CourseFactory.class.getClassLoader().getResourceAsStream("bean.properties");try {p.load(is);//遍历Properties集合对象Set<Object> keys = p.keySet();for (Object key : keys) {//根据键获取值(全类名)String className = p.getProperty((String) key);//获取字节码对象Class clazz = Class.forName(className);ICourse obj = (ICourse) clazz.newInstance();map.put((String)key,obj);}} catch (Exception e) {e.printStackTrace();}}public static ICourse create(String name) {return courses.get(name);}
}

三、工厂方法模式

工厂方法模式(Factory Method Pattern)是指定义一个创建对象的接口,但让实现这个接口的类来决定实例化哪个类,工厂方法让类的实例化推迟到子类中进行。在工厂方法模式中用户只需要关心所需产品对应的工厂,无需关心创建细节,而且加入新的产品符合开闭原则。

所以说,工厂方法模式比起简单工厂模式更加符合开闭原则

1、实例

先创建课程创建工厂:

public interface ICourseFactory {ICourse create();
}public class JavaCourseFactory implements ICourseFactory {public ICourse create() {return new JavaCourse();}
}public class PythonCourseFactory implements ICourseFactory {public ICourse create() {return new PythonCourse();}
}

课程的创建用工厂进行包装,此时我们客户端进行使用,只需要使用工厂进行创建即可:

public class FactoryMethodTest {public static void main(String[] args) {ICourseFactory factory = new PythonCourseFactory();ICourse course = factory.create();course.record();factory = new JavaCourseFactory();course = factory.create();course.record();}}

但是,这种场景似乎又回到了一开始,我们的客户端又跟对象的创建工厂耦合度十分高了。此时,我们应该考虑,使用简单工厂方法,对工厂进行封装。。。

public class CourseFactoryFactory {private static final Map<String, ICourseFactory> courses = new HashMap<>();static {courses.put("java", new JavaCourseFactory());courses.put("python", new PythonCourseFactory());}public static ICourseFactory create(String name) {return courses.get(name);}
}

2、什么时候该用工厂方法模式,而非简单工厂模式

之所以将某个代码块剥离出来,独立为函数或者类,原因是这个代码块的逻辑过于复杂,剥离之后能让代码更加清晰,更加可读、可维护。但是,如果代码块本身并不复杂,就几行代码而已,我们完全没必要将它拆分成单独的函数或者类。

基于这个设计思想,当对象的创建逻辑比较复杂,不只是简单的 new 一下就可以,而是要组合其他类对象,做各种初始化操作的时候,我们推荐使用工厂方法模式,将复杂的创建逻辑拆分到多个工厂类中,让每个工厂类都不至于过于复杂。而使用简单工厂模式,将所有的创建逻辑都放到一个工厂类中,会导致这个工厂类变得很复杂。

除此之外,在某些场景下,如果对象不可复用,那工厂类每次都要返回不同的对象。如果我们使用简单工厂模式来实现,就只能选择包含 if 分支逻辑的实现方式。如果我们还想避免烦人的 if-else 分支逻辑,这个时候,我们就推荐使用工厂方法模式。

四、抽象工厂模式

抽象工厂模式(Abstract Factory Pattern)使用并不常见,但是Spring中使用很广泛,是指提供一个创建一系列相关或相互依赖对象的接口,无需指定他们具体的类。客户端(应用层)不依赖于产品类实例如何被创建、实现等细节,强调的是一系列相关的产品对象(属于同一产品族)一起使用创建对象需要大量重复的代码。需要提供一个产品类的库,所有的产品以同样的接口出现,从而使客户端不依赖于具体实现。

前面介绍的工厂方法模式中考虑的是一类产品的生产,如畜牧场只养动物、电视机厂只生产电视机等。这些工厂只生产同种类产品,同种类产品称为同等级产品,也就是说:工厂方法模式只考虑生产同等级的产品,但是在现实生活中许多工厂是综合型的工厂,能生产多等级(种类) 的产品,如电器厂既生产电视机又生产洗衣机或空调,大学既有软件专业又有生物专业等。

抽象工厂模式将考虑多等级产品的生产,将同一个具体工厂所生产的位于不同等级的一组产品称为一个产品族,下图所示横轴是产品等级,也就是同一类产品;纵轴是产品族,也就是同一品牌的产品,同一品牌的产品产自同一个工厂。

1、实例

我们在前面的基础上,创建课程的同时,也要创建笔记、回放视频等等。

public interface INote {void edit();
}public class JavaNote implements INote {public void edit() {System.out.println("编写Java笔记");}
}public class PythonNote implements INote {public void edit() {System.out.println("编写Python笔记");}
}
public interface IVideo {void record();
}
public class JavaVideo implements IVideo {public void record() {System.out.println("录制Java视频");}
}
public class PythonVideo implements IVideo {public void record() {System.out.println("录制Python视频");}
}

此时,我们需要创建工厂:

public abstract class CourseFactory {public void init(){System.out.println("初始化基础数据");}protected abstract ICourse createCourse();protected abstract INote createNote();protected abstract IVideo createVideo();}public class JavaCourseFactory extends CourseFactory {public ICourse createCourse() {super.init();return new JavaCourse();}public INote createNote() {super.init();return new JavaNote();}public IVideo createVideo() {super.init();return new JavaVideo();}
}public class PythonCourseFactory extends CourseFactory {public ICourse createCourse() {super.init();return new PythonCourse();}public INote createNote() {super.init();return new PythonNote();}public IVideo createVideo() {super.init();return new PythonVideo();}
}

客户端这样使用:

JavaCourseFactory factory = new JavaCourseFactory();factory.createNote().edit();
factory.createVideo().record();
factory.createCourse().record()

六、源码分析

1、JDK-Collection.iterator方法

public class Demo {public static void main(String[] args) {List<String> list = new ArrayList<>();list.add("令狐冲");list.add("风清扬");list.add("任我行");//获取迭代器对象Iterator<String> it = list.iterator();//使用迭代器遍历while(it.hasNext()) {String ele = it.next();System.out.println(ele);}}
}

对上面的代码大家应该很熟,使用迭代器遍历集合,获取集合中的元素。而单列集合获取迭代器的方法就使用到了工厂方法模式。我们看通过类图看看结构:

Collection接口是抽象工厂类,ArrayList是具体的工厂类;Iterator接口是抽象商品类,ArrayList类中的Iter内部类是具体的商品类。在具体的工厂类中iterator()方法创建具体的商品类的对象。

2、Calendar

Calendar 的创建过程,就是使用的工厂模式:

private static Calendar createCalendar(TimeZone zone,Locale aLocale)
{CalendarProvider provider =LocaleProviderAdapter.getAdapter(CalendarProvider.class, aLocale).getCalendarProvider();if (provider != null) {try {return provider.getInstance(zone, aLocale);} catch (IllegalArgumentException iae) {// fall back to the default instantiation}}Calendar cal = null;if (aLocale.hasExtensions()) {String caltype = aLocale.getUnicodeLocaleType("ca");if (caltype != null) {switch (caltype) {case "buddhist":cal = new BuddhistCalendar(zone, aLocale);break;case "japanese":cal = new JapaneseImperialCalendar(zone, aLocale);break;case "gregory":cal = new GregorianCalendar(zone, aLocale);break;}}}if (cal == null) {// If no known calendar type is explicitly specified,// perform the traditional way to create a Calendar:// create a BuddhistCalendar for th_TH locale,// a JapaneseImperialCalendar for ja_JP_JP locale, or// a GregorianCalendar for any other locales.// NOTE: The language, country and variant strings are interned.if (aLocale.getLanguage() == "th" && aLocale.getCountry() == "TH") {cal = new BuddhistCalendar(zone, aLocale);} else if (aLocale.getVariant() == "JP" && aLocale.getLanguage() == "ja"&& aLocale.getCountry() == "JP") {cal = new JapaneseImperialCalendar(zone, aLocale);} else {cal = new GregorianCalendar(zone, aLocale);}}return cal;
}

3、slf4j

slf4j日志门面的实现,也是使用的工厂模式进行创建的。

public static Logger getLogger(Class<?> clazz) {Logger logger = getLogger(clazz.getName());if (DETECT_LOGGER_NAME_MISMATCH) {Class<?> autoComputedCallingClass = Util.getCallingClass();if (autoComputedCallingClass != null && nonMatchingClasses(clazz, autoComputedCallingClass)) {Util.report(String.format("Detected logger name mismatch. Given name: \"%s\"; computed name: \"%s\".", logger.getName(),autoComputedCallingClass.getName()));Util.report("See " + LOGGER_NAME_MISMATCH_URL + " for an explanation");}}return logger;
}

4、其他

DateFormat的getInstance方法也是用的工厂模式。

七、使用工厂模式实现数据库连接池

1、Pool


import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;/*** 自定义连接池 getInstance()返回POOL唯一实例,第一次调用时将执行构造函数* 构造函数Pool()调用驱动装载loadDrivers()函数;连接池创建createPool()函数 loadDrivers()装载驱动* createPool()建连接池 getConnection()返回一个连接实例 getConnection(long time)添加时间限制* freeConnection(Connection con)将con连接实例返回到连接池 getnum()返回空闲连接数* getnumActive()返回当前使用的连接数** @author Tom**/public abstract class Pool {public String propertiesName = "connection-INF.properties";private static Pool instance = null; // 定义唯一实例/*** 最大连接数*/protected int maxConnect = 100; // 最大连接数/*** 保持连接数*/protected int normalConnect = 10; // 保持连接数/*** 驱动字符串*/protected String driverName = null; // 驱动字符串/*** 驱动类*/protected Driver driver = null; // 驱动变量/*** 私有构造函数,不允许外界访问*/protected Pool() {try{init();loadDrivers(driverName);}catch(Exception e){e.printStackTrace();}}/*** 初始化所有从配置文件中读取的成员变量成员变量**/private void init() throws IOException {InputStream is = Pool.class.getResourceAsStream(propertiesName);Properties p = new Properties();p.load(is);this.driverName = p.getProperty("driverName");this.maxConnect = Integer.parseInt(p.getProperty("maxConnect"));this.normalConnect = Integer.parseInt(p.getProperty("normalConnect"));}/*** 装载和注册所有JDBC驱动程序** @param dri  接受驱动字符串*/protected void loadDrivers(String dri) {String driverClassName = dri;try {driver = (Driver) Class.forName(driverClassName).newInstance();DriverManager.registerDriver(driver);System.out.println("成功注册JDBC驱动程序" + driverClassName);} catch (Exception e) {System.out.println("无法注册JDBC驱动程序:" + driverClassName + ",错误:" + e);}}/*** 创建连接池*/public abstract void createPool();/**** (单例模式)返回数据库连接池 Pool 的实例** @param driverName 数据库驱动字符串* @return* @throws IOException* @throws ClassNotFoundException* @throws IllegalAccessException* @throws InstantiationException*/public static synchronized Pool getInstance() throws IOException,InstantiationException, IllegalAccessException,ClassNotFoundException {if (instance == null) {instance.init();instance = (Pool) Class.forName("org.jdbc.sqlhelper.Pool").newInstance();}return instance;}/*** 获得一个可用的连接,如果没有则创建一个连接,且小于最大连接限制** @return*/public abstract Connection getConnection();/**** 获得一个连接,有时间限制** @param time 设置该连接的持续时间(以毫秒为单位)* @return*/public abstract Connection getConnection(long time);/*** 将连接对象返回给连接池** @param con 获得连接对象*/public abstract void freeConnection(Connection con);/**** 返回当前空闲连接数** @return*/public abstract int getnum();/**** 返回当前工作的连接数** @return*/public abstract int getnumActive();/**** 关闭所有连接,撤销驱动注册(此方法为单例方法)*/protected synchronized void release() {// /撤销驱动try {DriverManager.deregisterDriver(driver);System.out.println("撤销JDBC驱动程序 " + driver.getClass().getName());} catch (SQLException e) {System.out.println("无法撤销JDBC驱动程序的注册:" + driver.getClass().getName());}}
}

2、DBConnectionPool


import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.*;
import java.util.Date;/*** 数据库链接池管理类** @author Tom**/
public final class DBConnectionPool extends Pool {private int checkedOut; //正在使用的连接数/*** 存放产生的连接对象容器*/private Vector<Connection> freeConnections = new Vector<Connection>(); //存放产生的连接对象容器private String passWord = null; // 密码private String url = null; // 连接字符串private String userName = null; // 用户名private static int num = 0;// 空闲连接数private static int numActive = 0;// 当前可用的连接数private static DBConnectionPool pool = null;// 连接池实例变量/*** 产生数据连接池* @return*/public static synchronized DBConnectionPool getInstance(){if(pool == null){pool = new DBConnectionPool();}return pool;}/*** 获得一个 数据库连接池的实例*/private DBConnectionPool() {try{init();for (int i = 0; i < normalConnect; i++) { // 初始normalConn个连接Connection c = newConnection();if (c != null) {freeConnections.addElement(c); //往容器中添加一个连接对象num++; //记录总连接数}}}catch(Exception e){e.printStackTrace();}}/*** 初始化* @throws IOException**/private void init() throws IOException{InputStream is = DBConnectionPool.class.getResourceAsStream(propertiesName);Properties p = new Properties();p.load(is);this.userName = p.getProperty("userName");this.passWord = p.getProperty("passWord");this.driverName = p.getProperty("driverName");this.url = p.getProperty("url");this.driverName = p.getProperty("driverName");this.maxConnect = Integer.parseInt(p.getProperty("maxConnect"));this.normalConnect = Integer.parseInt(p.getProperty("normalConnect"));}/*** 如果不再使用某个连接对象时,可调此方法将该对象释放到连接池** @param con*/public synchronized void freeConnection(Connection con) {freeConnections.addElement(con);num++;checkedOut--;numActive--;notifyAll(); //解锁}/*** 创建一个新连接** @return*/private Connection newConnection() {Connection con = null;try {if (userName == null) { // 用户,密码都为空con = DriverManager.getConnection(url);} else {con = DriverManager.getConnection(url, userName, passWord);}System.out.println("连接池创建一个新的连接");} catch (SQLException e) {System.out.println("无法创建这个URL的连接" + url);return null;}return con;}/*** 返回当前空闲连接数** @return*/public int getnum() {return num;}/*** 返回当前连接数** @return*/public int getnumActive() {return numActive;}/*** (单例模式)获取一个可用连接** @return*/public synchronized Connection getConnection() {Connection con = null;if (freeConnections.size() > 0) { // 还有空闲的连接num--;con = (Connection) freeConnections.firstElement();freeConnections.removeElementAt(0);try {if (con.isClosed()) {System.out.println("从连接池删除一个无效连接");con = getConnection();}} catch (SQLException e) {System.out.println("从连接池删除一个无效连接");con = getConnection();}} else if (maxConnect == 0 || checkedOut < maxConnect) { // 没有空闲连接且当前连接小于最大允许值,最大值为0则不限制con = newConnection();}if (con != null) { // 当前连接数加1checkedOut++;}numActive++;return con;}/*** 获取一个连接,并加上等待时间限制,时间为毫秒** @param timeout  接受等待时间(以毫秒为单位)* @return*/public synchronized Connection getConnection(long timeout) {long startTime = new Date().getTime();Connection con;while ((con = getConnection()) == null) {try {wait(timeout); //线程等待} catch (InterruptedException e) {}if ((new Date().getTime() - startTime) >= timeout) {return null; // 如果超时,则返回}}return con;}/*** 关闭所有连接*/public synchronized void release() {try {//将当前连接赋值到 枚举中Enumeration allConnections = freeConnections.elements();//使用循环关闭所用连接while (allConnections.hasMoreElements()) {//如果此枚举对象至少还有一个可提供的元素,则返回此枚举的下一个元素Connection con = (Connection) allConnections.nextElement();try {con.close();num--;} catch (SQLException e) {System.out.println("无法关闭连接池中的连接");}}freeConnections.removeAllElements();numActive = 0;} finally {super.release();}}/*** 建立连接池*/public void createPool() {pool = new DBConnectionPool();if (pool != null) {System.out.println("创建连接池成功");} else {System.out.println("创建连接池失败");}}
}

3、配置文件

driverName=com.microsoft.sqlserver.jdbc.SQLServerDriver
userName=sa
passWord=sa
url=jdbc:sqlserver://localhost:1433;DatabaseName=HousDB
maxConnect=100
normalConnect=10### SQL Server 2000 ###
#driver=com.microsoft.jdbc.sqlserver.SQLServerDriver
#url=jdbc:microsoft:sqlserver://127.0.0.1:1433;databaseName=test### JDBC - ODBC ###
#driver=sun.jcbc.odbc.JdbcOdbcDriver
#url=jdbc:odbc:test### Microsoft Access ###
#url=jdbc:odbc:driver={Microsoft Access Driver //(*.mdb)};DBQ=database\\NewAssetData.mdb
#driver=sun.jdbc.odbc.JdbcOdbcDriver### sql2005 ###
#driver=com.microsoft.sqlserver.jdbc.SQLServerDriver
#url=jdbc:sqlserver://localhost:1433;DatabaseName=BBSDataBase### oracle ####driver=oracle.jdbc.driver.OracleDriver
#url=jdbc:oracle:thin:@192.168.1.101:1521:ora9

4、ConManager


import java.sql.Connection;import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;/*** 数据库连接管理类* @author tanyongde*/
public class ConManager {private static Pool dbPool;private static ConManager instance = null;// 单例对象/*** 私有构造方法,禁止外部创建本类对象,想要获得本类对象,通过<code>getIstance</code>方法 使用了设计模式中的单例模式*/private ConManager() {}/*** 释放数据库连接对象*/protected static void closeCon(Connection con) {dbPool.freeConnection(con);}/*** 返回当前连接管理类的一个对象*/private static ConManager getInstance() {if (null == instance) {instance = new ConManager();}return instance;}/*** 从自定义数据库连接池中获得一个连接对象* @return*/protected static Connection getConnection(){Connection conn = null;try{if(dbPool == null){dbPool = DBConnectionPool.getInstance();}conn = dbPool.getConnection();}catch(Exception e){e.printStackTrace();}return conn;}/***  使用 JNDI 从 容器的数据库连接池中 获得一个连接对象* @param accessPool 是否通过容器连接池获得连接* 		  Tomcat 容器的字符串 "java:comp/env/...(数据源名)"* @return*/protected static Connection getConnection(String lookupStr) {Connection conn = null;try {ConManager.getInstance();//使用 JNDI 从Tomcat 容器的数据库连接池中 获得一个连接对象Context ctx = new InitialContext();DataSource ds = (DataSource)ctx.lookup(lookupStr);conn = ds.getConnection();} catch (Exception e1) {e1.printStackTrace();}return conn;}}

5、DataBaseCmd


import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;/*** 数据库操作类* 包含两个构造函数 <br/>* <b><font color="red">DataBaseCmd()</font></b> 使用自定义连接池获得连接<br/>* <b><font color="red">DataBaseCmd(String datasource)</font></b> 指定 JNDI 的数据源名称* @author tanyongde* */
public class DataBaseCmd {private PreparedStatement pstmt = null;// 连接语句private Connection con = null;// 获取连接对象private ResultSet rs = null;private String datasource = null; //指定使用的数据源/*** 默认构造器**/public DataBaseCmd(){}/*** 构造器* @param datasource 指定使用的JNDI查找的数据源名称* 	Tomcat 的数据源名为 java:comp/env/test*/public DataBaseCmd(String datasource){this.datasource = datasource;}/*** 初始化数据库连接对象*/private synchronized void initCon(){try {if(null == con){if(null == datasource || "".equals(datasource)){con = ConManager.getConnection();}else{con = ConManager.getConnection(datasource);}}} catch (Exception e) {e.printStackTrace();}}/*** 查询表格数据,此方法一般将单表中所有的数据查询出来,如果需要匹配条件查询,则最好在业务逻辑层或者界面层做数据解析或者在查询语句中直接带条件* @param sql 要执行的sql语句或者存储过程的名称* @param cmdtype 指定sql参数的类型:true为存储过程,false为sql语句* @param values 指定sql语句中的参数列表* @return 返回更新后的结果集* @throws Exception*/public ResultSet excuteQuery(String sql, boolean cmdtype,List values)throws Exception{try{initCon();//储存过程处理if(cmdtype){pstmt = con.prepareCall(sql);  //处理存储过程的语句集}else{pstmt = con.prepareStatement(sql);}if(values != null && values.size() >0){setValues(pstmt,values);}rs = pstmt.executeQuery();return rs;}catch(Exception ex){throw ex; }}/***  实现对数据的的增/删/改 * @param sql 要执行的sql语句或者存储过程的名称* @param cmdtype 指定sql参数的类型:true为存储过程,false为sql语句* @param values 存储过程或者sql语句中要指定的参数列表,无则为null* @return true执行成功,false执行失败* @throws Exception*/public int excuteUpdate(String sql,boolean cmdtype,List values)throws Exception{int noOfRows = 0;try{initCon();if(cmdtype){pstmt = con.prepareCall(sql);  //处理存储过程的语句集}else{pstmt = con.prepareStatement(sql);}if(values != null && values.size() >0){setValues(pstmt,values);}noOfRows = pstmt.executeUpdate();}catch(Exception ex){throw ex; }return noOfRows; }/*** 关闭连接*/public void closeConnection() {try {if (null != con && !con.isClosed()) {ConManager.closeCon(con);con = null;}} catch (SQLException e) {e.printStackTrace();}}/*** 关闭语句集*/public void closePstmt() {if (null != pstmt) {try {pstmt.close();pstmt = null;} catch (SQLException e) {e.printStackTrace();}}}/*** 关闭结果集*/public void closeResultSet() {if (null != rs) {try {rs.close();rs = null;} catch (SQLException e) {e.printStackTrace();}}}/*** 关闭所有数据库访问对象**/public void closeAll(){closePstmt();closeResultSet();closeConnection();}/*** 设定语句 得参数* @param pstmt 语句集 对象* @param values 指定 sql 语句中的参数列表* @throws SQLException*/private void setValues(PreparedStatement pstmt,List values)throws SQLException{for(int i=0;i<values.size();i++){Object v = values.get(i);pstmt.setObject(i+1, v);}}/*** (不建议使用的方法)使用 JNDI 的方式获取数据源时应使用此方法* 建议在构造器中直接传递参数* @param datasource 数据库连接使用的数据源名称* @deprecated*/public void setDatasource(String datasource) {this.datasource = datasource;}
}

更多推荐

设计模式之【工厂模式】,创建对象原来有这么多玩法

本文发布于:2024-02-11 08:16:04,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1679982.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:模式   玩法   对象   工厂   有这么多

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!