死磕设计模式-工厂模式
工厂模式的由来
在现实生活中我们都知道,原始社会自给自足(没有工厂)、农耕社会小作坊(简单工厂,民间酒坊)、工业革命流水线(工厂方法、自采自销)、现代产业链工厂(抽象工厂、富士康)
![]() | ![]() |
---|---|
![]() | ![]() |
我们项目代码同样也是由简而繁一步一步迭代而来,但对于调用者来说确是越来越简单化。
简单工厂模式
简单工厂模式是指由一个工厂对象决定创建哪一种产品类实例,但他不属于GOF23种设计模式.简单工厂适用于工厂类负责创建的对象较少的场景,且客户端只需要传入工厂参数,对于如果创建的逻辑对象不需要关心
接下来看代码,还是以库存为例.目前开设Java架构、大数据、等课程已经形成一个生态。我们可以定义一个课程标准
public interface ICourse {
/**
* 录制视频
*/
void record();
}
创建一个Java课程的实现JavaCourse类
public class JavaCourse implements ICourse{
public void record() {
System.out.println("录制Java课程");
}
}
看客户端调用代码,我们会这样写
public static void main(String[] args){
ICourse course = new JavaCourse();
course.record();
}
看上面代码,父类ICourse指向JavaCourse的引用,应用层代码需要依赖JavaCourse,如果业务扩展,我们继续增加PythonCourse或者更多,那么我们客户端的依赖会变得越来越臃肿。因此我们要想办法把这种依赖减弱,把创建细节隐藏。虽然目前的代码中,我们创建对象过程并不复杂,但从代码设计角度来讲不易于扩展。现在,我们用简单工厂模式对代码进行优化。线增加课程PythonCourse类:
public class PythonCourse implements ICourse{
public void record() {
System.out.println("录制Python课程");
}
}
创建CourseFactory类
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;
}
}
}
修改客户端调用代码
public class Text {
public static void main(String[] args){
CourseFactory factory = new CourseFactory();
factory.create("java");
}
}
当然,我们为了调用方便,可将factory的create改为静态方法,下面看一下类图:
客户端调用是简单了,但如果我们业务继续扩展,要增加前段课程,那么工厂的create() 就要根据产品链的丰富每次都要修改代码逻辑,不符合开闭原则。因此我们对简单工厂进行优化
采用反射技术:
public class CourseFactory {
public ICourse create(String className){
try {
if (!(null == className || "".equals(className))){
return (ICourse) Class.forName(className).newInstance();
}
} catch (Exception e){
e.printStackTrace();
}
return null;
}
}
客户端调用方法
public static void main(String[] args){
CourseFactory factory = new CourseFactory();
ICourse course = factory.create("com.sundablog.pattern.factory.JavaCourse");
course.record();
}
优化之后,产品不断丰富不需要修改CourseFactory中的代码。但是有个问题,方法参数是字符串,可控性有待提升,而且还需要强制类型。我们在修改一下代码
public class CourseFactory {
public ICourse create(Class<? extends ICourse> clazz){
try {
if (null != clazz){
return clazz.newInstance();
}
} catch (Exception e){
e.printStackTrace();
}
return null;
}
}
优化客户端代码
public static void main(String[] args){
CourseFactory factory = new CourseFactory();
ICourse course = factory.create(JavaCourse.class);
course.record();
}
在看一下类图
简单工厂模式在JDK源码也是无处不在,现在我们来举一个例子,例如Calendar类,看一下Calendar.getInstance()方法,下面打开是是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;
}
还有一个大家经常使用的Logback,我们可以看到LoggerFactory中有多个重载的方法getLogger();
public static Logger getLogger(String name) {
ILoggerFactory iLoggerFactory = getILoggerFactory();
return iLoggerFactory.getLogger(name);
}
public static Logger getLogger(Class clazz) {
return getLogger(clazz.getName());
}
简单工厂也有他的缺点:工厂类的职责相对过重,不易于扩展复杂的产品结构。
工厂方法模式
工厂方法模式是指定义一个创建对象的接口,但让实现这个接口的类来决定实例化那个类,工厂方法让类的实例化推迟到子类中进行.在工厂方法模式中用户只需要关系所需产品对应的工厂,无需关心创建细节,而加入新的产品符合开闭原则
工厂方法主要解决产品扩展问题,在简单工厂中,随着产品链的丰富,如果每个课程的创建逻辑有区别的话工厂职责会变得越来越多,有点万能工厂,并不便于维护。根据单一职责原则我们将职能继续拆分,专人干专事。Java课程由Java工厂创建。Python有Python工厂创建对工厂本身也做一个抽象。看下面代码
ICourseFactory类
public interface ICourseFactory {
ICourse create();
}
分别创建子工厂 JavaCourseFactory类
public class JavaCourseFactory implements ICourseFactory{
public ICourse create() {
return new JavaCourse();
}
}
PythonCourseFactory类
public class PythonCourseFactory implements ICourseFactory{
public ICourse create() {
return new PythonCourse();
}
}
看测试代码
public static void main(String[] args){
ICourseFactory factory = new JavaCourseFactory();
ICourse course = factory.create();
course.record();
}
看类图
工厂方法适用于以下场景:
1、创建对象需要大量重复代码
2、客户端(应用层)不依赖于产品类实例如何被创建、实现等细节。
3、一个类通过其子类来指定创建那个对象。
工厂方法也有缺点
1、类的个数容易过多,增加复杂度。
2、增加了系统的抽象性和理解难度
抽象工厂模式
抽象工厂模式是指提供一个创建一系列相关或相互依赖对象的接口,无需指定他们的具体类。客户端(应用层)不依赖于产品类实例如何被创建、实现等细节,强调的是一系列相关的产品对象(属于同一产品族)一起使用创建对象需要大量重复代码。需要提供一个产品类的库,所有的产品以同样的接口出现,从而使客户端不依赖具体实现。
在讲解抽象工厂之前,我们要了解两个概念产品等级和产品结构族,看下面的图
从上图中看出有正方形,圆形好菱形三种图形,相同颜色深浅的就代表同一个产品族,相同现状的代表同一个产品结构。同样可以从生活中举例,比如美的电器生产多种家电电器。那么上图中,颜色最深的正方形就代表美的洗衣机,颜色最深的圆形代表美的空调、颜色最深菱形代表的美的热水器,那么第二排颜色稍微浅一点菱形,代表海信热水器。同理,同一个产品线下还有格力热水器、格力空调、格力洗衣机
在看下图,最左侧的小房子我们就认为具体的工厂,有美的工厂,海信工厂,格力工厂。每个品牌的工厂都生产洗衣机、热水器和空调。
通过上面两张图的对比理解,相信大家对抽象工厂有了非常形象的理解。接下来我们看一个具体的业务场景而且用代码来实现,还是以课程为例,课程有了新的标准,每个课程不仅要提供课程的录播视频,而且还要提供老师的空调笔记。相当于现在业务变更为同一个课程不单纯一个课程信息,要同时包含录播视频、课堂笔记还要提供源代码才能构成一个完成的课程,在产品等级中增加两个产品IVideo录播视频和INote课堂笔记
IVideo接口
public interface IVideo {
void record();
}
INote接口
public interface INote {
void edit();
}
创建抽象工厂
public abstract class CourseFactory {
public void init(){
System.out.println("初始化基础数据");
}
protected abstract INote createNote();
protected abstract IVideo createVideo();
}
接下来创建Java产品族,java视频JavaVideo
public class JavaVideo implements IVideo{
public void record() {
System.out.println("录制Java视频");
}
}
扩展产品等级Java课堂笔记JavaNote类
public class JavaNote implements INote {
public void edit() {
System.out.println("编写Java笔记");
}
}
创建Java产品族的具有工厂类 JavaCourseFactory
public class JavaCourseFactory extends CourseFactory{
@Override
public INote createNote() {
super.init();
return new JavaNote();
}
@Override
public IVideo createVideo() {
super.init();
return new JavaVideo();
}
}
然后创建Python产品,Python视频PythonVideo类
public class PythonVideo implements IVideo {
public void record() {
System.out.println("录制Python视频");
}
}
扩展产品等级Python课堂笔记PythonNote类
public class PythonNote implements INote{
public void edit() {
System.out.println("编写Python笔记");
}
}
创建Python产品族的具有工厂类 PythonCourseFactory
public class PythonCourseFactory extends CourseFactory{
@Override
public INote createNote() {
super.init();
return new PythonNote();
}
@Override
public IVideo createVideo() {
super.init();
return new PythonVideo();
}
}
来看客户端调用:
public static void main(String[] args){
JavaCourseFactory factory = new JavaCourseFactory();
factory.createNote().edit();
factory.createVideo().record();
}
上面的代码完整描述了两个产品组Java课程和Python课程,也描述了两个产品等级视频和笔记。抽象工厂非常完成清晰的描述这样一层复杂的关系。但是,不知道你们有没有发现,如果我们在继续扩展产品等级,将源码Source也加入课程中,那我们的代码从抽象工厂,到具体工厂要全部调整,很显然不符合开闭原则,因此抽象工厂也是有缺点的:
1、规定了所有可能被创建的工厂,产品族中扩展新的产品困难,需要修改抽象工厂接口。
2、增加了系统的抽象和理解难度
但在实际应用中,我们千万不能犯强迫症甚至有洁癖。在实际需求中产品等级结构升级是非常正常的一件事情。我们可以根据实际情况,只要不是频繁升级,可以不遵循开闭原则。代码每半年升级一次或者每年升级一次又有何不可呢?
利用工厂模式重构的实践案例
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()返回当前使用的连接数
*
*
*/
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());
}
}
}
DBConnectionPool类
package org.jdbc.sqlhelper;
import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.*;
import java.util.Date;
/**
* 数据库链接池管理类
*
*/
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) { // 当前连接数加1
checkedOut++;
}
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("创建连接池失败");
}
}
}