竹笋

注册

 

发新话题 回复该主题

万字长文手写数据库连接池,让抽象工厂不再 [复制链接]

1#
北京哪个医院治疗白癜风安全性高 https://m.39.net/disease/a_z4ok395.html

本文节选自《设计模式就该这样学》

1关于产品等级结构和产品族

在讲解抽象工厂之前,我们要了解两个概念:产品等级结构和产品族,如下图所示。

上图中有正方形、圆形和菱形3种图形,相同颜色、相同深浅的代表同一个产品族,相同形状的代表同一个产品等级结构。同样可以从生活中来举例,比如,美的电器生产多种家用电器,那么上图中,颜色最深的正方形就代表美的洗衣机,颜色最深的圆形代表美的空调,颜色最深的菱形代表美的热水器,颜色最深的一排都属于美的品牌,都属于美的电器这个产品族。再看最右侧的菱形,颜色最深的被指定了代表美的热水器,那么第二排颜色稍微浅一点的菱形代表海信热水器。同理,同一产品族下还有格力洗衣机、格力空调、格力热水器。

再看下图,最左侧的小房子被认为是具体的工厂,有美的工厂、海信工厂、格力工厂。每个品牌的工厂都生产洗衣机、空调和热水器。

通过上面两张图的对比理解,相信大家对抽象工厂有了非常形象的理解。

2抽象工厂模式的通用写法

以下是抽象工厂模式的通用写法。

publicclassClient{publicstaticvoidmain(String[]args){IFactoryfactory=newConcreteFactoryA();factory.makeProductA();factory.makeProductB();factory=newConcreteFactoryB();factory.makeProductA();factory.makeProductB();}//抽象工厂类publicinterfaceIFactory{IProductAmakeProductA();IProductBmakeProductB();}//产品A抽象publicinterfaceIProductA{voiddoA();}//产品B抽象publicinterfaceIProductB{voiddoB();}//产品族A的具体产品AstaticclassConcreteProductAWithFamilyAimplementsIProductA{publicvoiddoA(){System.out.println("TheProductAbepartofFamilyA");}}//产品族A的具体产品BstaticclassConcreteProductBWithFamilyAimplementsIProductB{publicvoiddoB(){System.out.println("TheProductBbepartofFamilyA");}}//产品族B的具体产品AstaticclassConcreteProductAWithFamilyBimplementsIProductA{publicvoiddoA(){System.out.println("TheProductAbepartofFamilyB");}}//产品族B的具体产品BstaticclassConcreteProductBWithFamilyBimplementsIProductB{publicvoiddoB(){System.out.println("TheProductBbepartofFamilyB");}}//具体工厂类AstaticclassConcreteFactoryAimplementsIFactory{publicIProductAmakeProductA(){returnnewConcreteProductAWithFamilyA();}publicIProductBmakeProductB(){returnnewConcreteProductBWithFamilyA();}}//具体工厂类BstaticclassConcreteFactoryBimplementsIFactory{publicIProductAmakeProductA(){returnnewConcreteProductAWithFamilyB();}publicIProductBmakeProductB(){returnnewConcreteProductBWithFamilyB();}}}

3使用抽象工厂模式支持产品扩展

我们来看一个具体的业务场景,并且用代码来实现。还是以网络课程为例,一般课程研发会有一定的标准,每个课程不仅要提供课程的录播视频,还要提供老师的课堂笔记。相当于现在的业务变更为同一个课程不单纯是一个课程信息,要同时包含录播视频、课堂笔记,甚至要提供源码才能构成一个完整的课程。首先在产品等级中增加两个产品:录播视频IVideo和课堂笔记INote。IVideo接口的代码如下。

publicinterfaceIVideo{voidrecord();}

INote接口的代码如下。

publicinterfaceINote{voidedit();}

然后创建一个抽象工厂CourseFactory类。

/***抽象工厂是用户的主入口*在Spring中应用得最为广泛的一种设计模式*易于扩展*CreatedbyTom*/publicabstractclassCourseFactory{publicvoidinit(){System.out.println("初始化基础数据");}protectedabstractINotecreateNote();protectedabstractIVideocreateVideo();}

接下来创建Java产品族,Java视频JavaVideo类的代码如下。

publicclassJavaVideoimplementsIVideo{publicvoidrecord(){System.out.println("录制Java视频");}}

扩展产品等级Java课堂笔记JavaNote类。

publicclassJavaNoteimplementsINote{publicvoidedit(){System.out.println("编写Java笔记");}}

创建Java产品族的具体工厂JavaCourseFactory。

publicclassJavaCourseFactoryextendsCourseFactory{publicINotecreateNote(){super.init();returnnewJavaNote();}publicIVideocreateVideo(){super.init();returnnewJavaVideo();}}

随后创建Python产品族,Python视频PythonVideo类的代码如下。

publicclassPythonVideoimplementsIVideo{publicvoidrecord(){System.out.println("录制Python视频");}}

扩展产品等级Python课堂笔记PythonNote类。

publicclassPythonNoteimplementsINote{publicvoidedit(){System.out.println("编写Python笔记");}}

创建Python产品族的具体工厂PythonCourseFactory。

publicclassPythonCourseFactoryimplementsCourseFactory{publicINotecreateNote(){returnnewPythonNote();}publicIVideocreateVideo(){returnnewPythonVideo();}}

最后来看客户端调用代码。

publicstaticvoidmain(String[]args){JavaCourseFactoryfactory=newJavaCourseFactory();factory.createNote().edit();factory.createVideo().record();}

上面代码完整地描述了Java课程和Python课程两个产品族,也描述了视频和笔记两个产品等级。抽象工厂非常完美、清晰地描述了这样一层复杂的关系。但是,不知道大家有没有发现,如果再继续扩展产品等级,将源码Source也加入课程中,则代码从抽象工厂到具体工厂要全部调整,这显然不符合开闭原则。

4使用抽象工厂模式重构数据库连接池

还是演示课堂开始的JDBC操作案例,我们每次操作都需要重新创建数据库连接。其实每次创建都非常耗费性能,消耗业务调用时间。我们使用抽象工厂模式,将数据库连接预先创建好,放到容器中缓存着,当业务调用时就只需现取现用。我们来看代码。Pool抽象类的代码如下。

/***自定义连接池getInstance()返回POOL唯一实例,第一次调用时将执行构造函数*构造函数Pool()调用驱动装载loadDrivers()函数;*连接池创建createPool()函数,loadDrivers()装载驱动*createPool()创建连接池,getConnection()返回一个连接实例,*getConnection(longtime)添加时间限制*freeConnection(Connectioncon)将con连接实例返回连接池,getnum()返回空闲连接数*getnumActive()返回当前使用的连接数**

authorTom**/publicabstractclassPool{publicStringpropertiesName="connection-INF.properties";privatestaticPoolinstance=null;//定义唯一实例/***最大连接数*/protectedintmaxConnect=;//最大连接数/***保持连接数*/protectedintnormalConnect=10;//保持连接数/***驱动字符串*/protectedStringdriverName=null;//驱动字符串/***驱动类*/protectedDriverdriver=null;//驱动变量/***私有构造函数,不允许外界访问*/protectedPool(){try{init();loadDrivers(driverName);}catch(Exceptione){e.printStackTrace();}}/***初始化所有从配置文件中读取的成员变量*/privatevoidinit()throwsIOException{InputStreamis=Pool.class.getResourceAsStream(propertiesName);Propertiesp=newProperties();p.load(is);this.driverName=p.getProperty("driverName");this.maxConnect=Integer.parseInt(p.getProperty("maxConnect"));this.normalConnect=Integer.parseInt(p.getProperty("normalConnect"));}/***装载和注册所有JDBC驱动程序*

paramdri接收驱动字符串*/protectedvoidloadDrivers(Stringdri){StringdriverClassName=dri;try{driver=(Driver)Class.forName(driverClassName).newInstance();DriverManager.registerDriver(driver);System.out.println("成功注册JDBC驱动程序"+driverClassName);}catch(Exceptione){System.out.println("无法注册JDBC驱动程序:"+driverClassName+",错误:"+e);}}/***创建连接池*/publicabstractvoidcreatePool();/****(单例模式)返回数据库连接池Pool的实例**

paramdriverName数据库驱动字符串*

return*

throwsIOException*

throwsClassNotFoundException*

throwsIllegalAccessException*

throwsInstantiationException*/publicstaticsynchronizedPoolgetInstance()throwsIOException,InstantiationException,IllegalAccessException,ClassNotFoundException{if(instance==null){instance=(Pool)Class.forName("org.e_book.sqlhelp.Pool").newInstance();}returninstance;}/***获得一个可用的连接,如果没有,则创建一个连接,并且小于最大连接限制*

return*/publicabstractConnectiongetConnection();/***获得一个连接,有时间限制*

paramtime设置该连接的持续时间(以毫秒为单位)*

return*/publicabstractConnectiongetConnection(longtime);/***将连接对象返回连接池*

paramcon获得连接对象*/publicabstractvoidfreeConnection(Connectioncon);/***返回当前空闲的连接数*

return*/publicabstractintgetnum();/***返回当前工作的连接数*

return*/publicabstractintgetnumActive();/***关闭所有连接,撤销驱动注册(此方法为单例方法)*/protectedsynchronizedvoidrelease(){//撤销驱动try{DriverManager.deregisterDriver(driver);System.out.println("撤销JDBC驱动程序"+driver.getClass().getName());}catch(SQLExceptione){System.out.println("无法撤销JDBC驱动程序的注册:"+driver.getClass().getName());}}}

DBConnectionPool数据库连接池的代码如下。

/***数据库连接池管理类*

authorTom**/publicfinalclassDBConnectionPoolextendsPool{privateintcheckedOut;//正在使用的连接数/***存放产生的连接对象容器*/privateVectorConnectionfreeConnections=newVectorConnection();//存放产生的连接对象容器privateStringpassWord=null;//密码privateStringurl=null;//连接字符串privateStringuserName=null;//用户名privatestaticintnum=0;//空闲连接数privatestaticintnumActive=0;//当前可用的连接数privatestaticDBConnectionPoolpool=null;//连接池实例变量/***产生数据连接池*

return*/publicstaticsynchronizedDBConnectionPoolgetInstance(){if(pool==null){pool=newDBConnectionPool();}returnpool;}/***获得一个数据库连接池的实例*/privateDBConnectionPool(){try{init();for(inti=0;inormalConnect;i++){//初始normalConn个连接Connectionc=newConnection();if(c!=null){freeConnections.addElement(c);//往容器中添加一个连接对象num++;//记录总连接数}}}catch(Exceptione){e.printStackTrace();}}/***初始化*

throwsIOException*/privatevoidinit()throwsIOException{InputStreamis=DBConnectionPool.class.getResourceAsStream(propertiesName);Propertiesp=newProperties();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"));}/***如果不再使用某个连接对象,则可调此方法将该对象释放到连接池*

paramcon*/publicsynchronizedvoidfreeConnection(Connectioncon){freeConnections.addElement(con);num++;checkedOut--;numActive--;notifyAll();//解锁}/***创建一个新连接*

return*/privateConnectionnewConnection(){Connectioncon=null;try{if(userName==null){//用户、密码都为空con=DriverManager.getConnection(url);}else{con=DriverManager.getConnection(url,userName,passWord);}System.out.println("连接池创建一个新的连接");}catch(SQLExceptione){System.out.println("无法创建这个URL的连接"+url);returnnull;}returncon;}/***返回当前空闲的连接数*

return*/publicintgetnum(){returnnum;}/***返回当前可用的连接数*

return*/publicintgetnumActive(){returnnumActive;}/***(单例模式)获取一个可用连接*

return*/publicsynchronizedConnectiongetConnection(){Connectioncon=null;if(freeConnections.size()0){//还有空闲的连接num--;con=(Connection)freeConnections.firstElement();freeConnections.removeElementAt(0);try{if(con.isClosed()){System.out.println("从连接池删除一个无效连接");con=getConnection();}}catch(SQLExceptione){System.out.println("从连接池删除一个无效连接");con=getConnection();}//没有空闲连接且当前连接小于最大允许值,若最大值为0,则不限制}elseif(maxConnect==0

checkedOutmaxConnect){con=newConnection();}if(con!=null){//当前连接数加1checkedOut++;}numActive++;returncon;}/***获取一个连接,并加上等待时间限制,时间为毫秒*

paramtimeout接受等待时间(以毫秒为单位)*

return*/publicsynchronizedConnectiongetConnection(longtimeout){longstartTime=newDate().getTime();Connectioncon;while((con=getConnection())==null){try{wait(timeout);//线程等待}catch(InterruptedExceptione){}if((newDate().getTime()-startTime)=timeout){returnnull;//如果超时,则返回}}returncon;}/***关闭所有连接*/publicsynchronizedvoidrelease(){try{//将当前连接赋值到枚举中EnumerationallConnections=freeConnections.elements();//使用循环关闭连接池中的所用连接while(allConnections.hasMoreElements()){//如果此枚举对象至少还有一个可提供的元素,则返回此枚举的下一个元素Connectioncon=(Connection)allConnections.nextElement();try{con.close();num--;}catch(SQLExceptione){System.out.println("无法关闭连接池中的连接");}}freeConnections.removeAllElements();numActive=0;}finally{super.release();}}/***建立连接池*/publicvoidcreatePool(){pool=newDBConnectionPool();if(pool!=null){System.out.println("创建连接池成功");}else{System.out.println("创建连接池失败");}}}

5抽象工厂模式在Spring源码中的应用

在Spring中,所有工厂都是BeanFactory的子类。通过对BeanFactory的实现,我们可以从Spring的容器访问Bean。根据不同的策略调用getBean()方法,从而获得具体对象。

publicinterfaceBeanFactory{StringFACTORY_BEAN_PREFIX="";ObjectgetBean(Stringname)throwsBeansException;TTgetBean(Stringname,

NullableClassTrequiredType)throwsBeansException;ObjectgetBean(Stringname,Object...args)throwsBeansException;TTgetBean(ClassTrequiredType)throwsBeansException;TTgetBean(ClassTrequiredType,Object...args)throwsBeansException;booleancontainsBean(Stringname);booleanisSingleton(Stringname)throwsNoSuchBeanDefinitionException;booleanisPrototype(Stringname)throwsNoSuchBeanDefinitionException;booleanisTypeMatch(Stringname,ResolvableTypetypeToMatch)throwsNoSuchBeanDefinitionException;booleanisTypeMatch(Stringname,

NullableClass?typeToMatch)throwsNoSuchBeanDefinitionException;

NullableClass?getType(Stringname)throwsNoSuchBeanDefinitionException;String[]getAliases(Stringname);}

BeanFactory的子类主要有ClassPathXmlApplicationContext、XmlWebApplicationContext、StaticWebApplicationContext、StaticPortletApplicationContext、GenericApplicationContext和StaticApplicationContext。在Spring中,DefaultListableBeanFactory实现了所有工厂的公共逻辑。

本文为“Tom弹架构”原创,转载请注明出处。技术在于分享,我分享我快乐!如果本文对您有帮助,欢迎

分享 转发
TOP
发新话题 回复该主题