工厂模式与DAO模式 http://gaojiewyh.javaeye.com/blog/419199

关键字: io流、反射机制、properties、dao、单例

      工厂模式是设计模式中较简单的模式,但在项目的开发过程中会常常用到它。下面分析下工厂模式,提出一种在项目中比较可行的工厂方法的实现。同时,结合单例模式,构建DAO设计模式。

工厂模式

1、工厂模式的组成

简单工厂模式又叫静态工厂模式,顾名思义,它是用来实例化目标类的静态类。它由三种角色组成:

抽象产品角色(Product): 它一般是具体产品继承的父类或者实现的接口。在 java 中由接口或者抽象类来实现。

      具体产品角色(Concert Product): 工厂类所创建的对象就是此角色的实例。在 java 中由一个具体类实现。

工厂类角色(Creator): 这是本模式的核心,含有一定的商业逻辑和判断逻辑。在 java 中它往往由一个具体类实现。

 

2、工厂模式UML图

 



 

 

 3、简单代码的实现

 

Java代码
  1. interface  Fruit{      
  2.         public   void  grow();      
  3.         public   void  eat();      
  4. }  
  5.       
  6. pulbic class  Apple  implements  Fruit{      
  7.         public   void  grow(){      
  8.                 System.out.println("苹果在生长..." );      
  9.         }      
  10.         public   void  eat(){      
  11.                 System.out.println("吃苹果..." );      
  12.         }      
  13. }    
  14.     
  15. public   class  Orange  implements  Fruit{      
  16.         public   void  grow(){      
  17.                 System.out.println("橘子在生长..." );      
  18.         }      
  19.         public   void  eat(){      
  20.                 System.out.println("吃橘子..." );      
  21.         }      
  22. }     
  23.    
  24. pulbic class  Factory{      
  25.         public   static  Fruit getFruit(String name){      
  26.                 Fruit f = null ;      
  27.                 if  ( "apple" .equal(name)){      
  28.                         f = new  Apple();      
  29.                 }else   if  (( "orange" .equal(name)){    ){      
  30.                         f = new  Orange();      
  31.                 }      
  32.                 return  f;      
  33.         }      
  34. }    
interface Fruit{    
        public void grow();    
        public void eat();    
}
    
pulbic class Apple implements Fruit{    
        public void grow(){    
                System.out.println("苹果在生长...");    
        }    
        public void eat(){    
                System.out.println("吃苹果...");    
        }    
}  
  
public class Orange implements Fruit{    
        public void grow(){    
                System.out.println("橘子在生长...");    
        }    
        public void eat(){    
                System.out.println("吃橘子...");    
        }    
}   
 
pulbic class Factory{    
        public static Fruit getFruit(String name){    
                Fruit f = null;    
                if ("apple".equal(name)){    
                        f = new Apple();    
                }else if (("orange".equal(name)){    ){    
                        f = new Orange();    
                }    
                return f;    
        }    
}  
Java代码
  1.      
  2. public   class  Clinet{      
  3.         public   static   void  main(String args[]){      
  4.                 Fruit f = Factory.getFruit(“apple”);      
  5.                 f.grow();      
  6.         }      
  7. }  
   
public class Clinet{    
        public static void main(String args[]){    
                Fruit f = Factory.getFruit(“apple”);    
                f.grow();    
        }    
}

 

 

      从开闭原则上来分析下简单工厂模式。当增加了一种水果时候,只要符合抽象产品制定的合同,那么只要通知工厂类知道就可以被 客户使用了。那么对于产品部分来说,它是符合开闭原则的——对扩展开放、对修改关闭;但是工厂部分好像不太理想,因为每增加一一种水果,都要在工厂类中增 加相应的商业逻辑和判断逻辑,这显然是违背开闭原则的。

      为了符合开闭原则,同时考虑以后代码的维护性,我们采用java的反射机制及propertie综合应用,使得配置与程序分离,程序的修改只与配置文件有关,某一部分的修改不影响其他程序。

 4、改造后的代码

Java代码 
  1. /**  
  2.  * @author gao_jie  
  3.  *  
  4.  */   
  5. public   interface  Fruit {  
  6.     public   void  grow();      
  7.     public   void  eat();      
  8. }  
  9.   
  10. public   class  Apple  implements  Fruit {  
  11.     /* (non-Javadoc)  
  12.      * @see com.cvicse.Ifactory.Fruit#grow()  
  13.      */   
  14.     public   void  grow() {  
  15.         System.out.println("苹果在生长..." );  
  16.     }  
  17.     /* (non-Javadoc)  
  18.      * @see com.cvicse.Ifactory.Fruit#eat()  
  19.      */   
  20.     public   void  eat() {  
  21.         System.out.println("吃苹果..." );  
  22.     }  
  23. }  
  24.   
  25. public   class  Orange  implements  Fruit {  
  26.     /* (non-Javadoc)  
  27.      * @see com.cvicse.Ifactory.Fruit#grow()  
  28.      */   
  29.     public   void  grow() {  
  30.         System.out.println("橘子在生长..." );  
  31.     }  
  32.   
  33.     /* (non-Javadoc)  
  34.      * @see com.cvicse.Ifactory.Fruit#eat()  
  35.      */   
  36.     public   void  eat() {  
  37.         System.out.println("吃橘子..." );  
  38.     }  
  39. }  
  40.   
  41. public   class  Banana  implements  Fruit {  
  42.     /* (non-Javadoc)  
  43.      * @see com.cvicse.Ifactory.Fruit#grow()  
  44.      */   
  45.     public   void  grow() {  
  46.         System.out.println("香蕉在生长..." );  
  47.     }  
  48.   
  49.     /* (non-Javadoc)  
  50.      * @see com.cvicse.Ifactory.Fruit#eat()  
  51.      */   
  52.     public   void  eat() {  
  53.         System.out.println("吃香蕉..." );  
  54.     }  
  55. }  
  56.   
  57. public   class  FruitFactory {  
  58.     public   static  Fruit getFruit(String className) {  
  59.         Fruit f = null ;  
  60.         try  {  
  61.             // 采用类的反射机制生成实例   
  62.             f = (Fruit) Class.forName(className).newInstance();  
  63.         } catch  (Exception e) {  
  64.             throw   new  ExceptionInInitializerError(e);  
  65.         }  
  66.         return  f;  
  67.     }  
  68. }  
  69.   
  70. /**  
  71.  * @author gao_jie  
  72.  *   
  73.  */   
  74. public   class  PropertyOperate {  
  75.   
  76.     private  Properties pro =  null ;  
  77.   
  78.     public  PropertyOperate() {  
  79.         this .pro =  new  Properties();  
  80.         this .load();  
  81.     }  
  82.   
  83.     // 设置一个返回方法   
  84.     public  Properties getPro() {  
  85.         return   this .pro;  
  86.     }  
  87.     // 加载配置文件内容   
  88.     private   void  load() {  
  89.         try  {  
  90.             // 文件流输入方式   
  91.             InputStream file = this .getClass().getClassLoader()  
  92.                     .getResourceAsStream("classInfor.properties" );  
  93.             pro.load(file);  
  94.         } catch  (IOException e) {  
  95.             // TODO Auto-generated catch block   
  96.             e.printStackTrace();  
  97.         }  
  98.     }    
  99. }  
  100.   
  101. classInfor.properties  
  102.   
  103. apple=com.cvicse.factory.Apple  
  104. orange=com.cvicse.factory.Orange  
  105. banana=com.cvicse.factory.Banana  
  106.   
  107. /**  
  108.  * @author gao_jie  
  109.  *   
  110.  */   
  111. public   class  Client {  
  112.   
  113.     /**  
  114.      * @param args  
  115.      */   
  116.     public   static   void  main(String[] args) {  
  117.         // 获取文件名字路径   
  118.         Properties p = new  PropertyOperate().getPro();  
  119.         // 进一步扩展,现在可以由用户自己输入要使用的类型   
  120.         Fruit f = FruitFactory.getFruit(p.getProperty(args[0 ]));  
  121.         f.grow();  
  122.     }  
  123. }  
/**
 * @author gao_jie
 *
 */
public interface Fruit {
    public void grow();    
    public void eat();    
}

public class Apple implements Fruit {
	/* (non-Javadoc)
	 * @see com.cvicse.Ifactory.Fruit#grow()
	 */
	public void grow() {
		System.out.println("苹果在生长...");
	}
	/* (non-Javadoc)
	 * @see com.cvicse.Ifactory.Fruit#eat()
	 */
	public void eat() {
		System.out.println("吃苹果...");
	}
}

public class Orange implements Fruit {
	/* (non-Javadoc)
	 * @see com.cvicse.Ifactory.Fruit#grow()
	 */
	public void grow() {
		System.out.println("橘子在生长...");
	}

	/* (non-Javadoc)
	 * @see com.cvicse.Ifactory.Fruit#eat()
	 */
	public void eat() {
		System.out.println("吃橘子...");
	}
}

public class Banana implements Fruit {
	/* (non-Javadoc)
	 * @see com.cvicse.Ifactory.Fruit#grow()
	 */
	public void grow() {
		System.out.println("香蕉在生长...");
	}

	/* (non-Javadoc)
	 * @see com.cvicse.Ifactory.Fruit#eat()
	 */
	public void eat() {
		System.out.println("吃香蕉...");
	}
}

public class FruitFactory {
	public static Fruit getFruit(String className) {
		Fruit f = null;
		try {
			// 采用类的反射机制生成实例
			f = (Fruit) Class.forName(className).newInstance();
		} catch (Exception e) {
			throw new ExceptionInInitializerError(e);
		}
		return f;
	}
}

/**
 * @author gao_jie
 * 
 */
public class PropertyOperate {

	private Properties pro = null;

	public PropertyOperate() {
		this.pro = new Properties();
		this.load();
	}

	// 设置一个返回方法
	public Properties getPro() {
		return this.pro;
	}
	// 加载配置文件内容
	private void load() {
		try {
			// 文件流输入方式
			InputStream file = this.getClass().getClassLoader()
					.getResourceAsStream("classInfor.properties");
			pro.load(file);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}  
}

classInfor.properties

apple=com.cvicse.factory.Apple
orange=com.cvicse.factory.Orange
banana=com.cvicse.factory.Banana

/**
 * @author gao_jie
 * 
 */
public class Client {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// 获取文件名字路径
		Properties p = new PropertyOperate().getPro();
		// 进一步扩展,现在可以由用户自己输入要使用的类型
		Fruit f = FruitFactory.getFruit(p.getProperty(args[0]));
		f.grow();
	}
}

 DAO模式

DAO设计模式是在项目开发过程中一个常见的设计模式,我们将在随后的文章中具体讲解,现在只贴出具体实现代码,以供参考。

典型实现代码

Java代码 
  1. package  com.cvice.dao;  
  2.   
  3. public   interface  UserDAO {  
  4.     public   void  insert();    //插入操作   
  5.     public   void  delet();     //删除操作   
  6. }  
  7.   
  8. package  com.cvicse.dao.impl;  
  9.   
  10. import  com.cvice.dao.UserDAO;  
  11.   
  12. /**  
  13.  * @author Administrator  
  14.  *  
  15.  */   
  16. public   class  UserDAOImpl  implements  UserDAO{  
  17.   
  18.     public   void  delet() {  
  19.         // TODO Auto-generated method stub   
  20.         System.out.println("删除记录成功" );  
  21.     }  
  22.   
  23.     public   void  insert() {  
  24.         // TODO Auto-generated method stub   
  25.         System.out.println("插入记录成功" );  
  26.     }  
  27. }  
  28.   
  29. package  com.cvice.dao;  
  30.   
  31. import  java.io.IOException;  
  32. import  java.io.InputStream;  
  33. import  java.util.Properties;  
  34.   
  35. /**  
  36.  * @author Administrator  
  37.  *   
  38.  */   
  39.   
  40. public   class  DaoFactory {  
  41.       
  42.     private   static  UserDAO userDao =  null ; //DAO层用户接口对象   
  43.     private   static  DaoFactory instance =  new  DaoFactory();  
  44.     private   static  Properties pro; //配置文件对象   
  45.   
  46.     private  DaoFactory() {  
  47.         try  {  
  48.             //初始化配置文件   
  49.             pro = new  Properties();  
  50.             //采用类加载器方法读取配置文件信息到字节流对象,采用类加载灵活,不用写死   
  51.             InputStream inputStream = DaoFactory.class .getClassLoader()  
  52.                     .getResourceAsStream("db.properties" );  
  53.             //加载字节流对象   
  54.             pro.load(inputStream);  
  55.         } catch  (IOException e) {  
  56.             throw   new  ExceptionInInitializerError(e);  
  57.         }  
  58.     }  
  59.   
  60.     /**  
  61.      * 单例模式获取唯一实例  
  62.      * @return  
  63.      */   
  64.     public   static  DaoFactory getInstance() {   
  65.         return  instance;  
  66.     }  
  67.   
  68.     /**  
  69.      * 根据配置文件的名字获取类的名字,采用反射机制获取其对象  
  70.      * @param Key  
  71.      * @return  
  72.      */   
  73.     public  UserDAO getUserDAO(String Key) {  
  74.         try  {  
  75.             String className=(String) pro.get(Key);  
  76.             userDao = (UserDAO) Class.forName(className).newInstance();  
  77.         } catch  (InstantiationException e) {  
  78.             // TODO Auto-generated catch block   
  79.             e.printStackTrace();  
  80.         } catch  (IllegalAccessException e) {  
  81.             // TODO Auto-generated catch block   
  82.             e.printStackTrace();  
  83.         } catch  (ClassNotFoundException e) {  
  84.             // TODO Auto-generated catch block   
  85.             e.printStackTrace();  
  86.         }  
  87.         return  userDao;  
  88.     }  
  89. }  
  90.   
  91. package  com.cvicse.Test;  
  92.   
  93. import  com.cvice.dao.DaoFactory;  
  94. import  com.cvice.dao.UserDAO;  
  95.   
  96. /**  
  97.  * @author Administrator  
  98.  *  
  99.  */   
  100. public   class  DAOTest {  
  101.   
  102.     /**  
  103.      * @param args  
  104.      */   
  105.     public   static   void  main(String[] args) {  
  106.         // TODO Auto-generated method stub   
  107.         UserDAO userDao=DaoFactory.getInstance().getUserDAO("userDao" );  
  108.         userDao.delet();  
  109.     }  
  110.   
  111. }  
package com.cvice.dao;

public interface UserDAO {
	public void insert();	//插入操作
	public void delet();	//删除操作
}

package com.cvicse.dao.impl;

import com.cvice.dao.UserDAO;

/**
 * @author Administrator
 *
 */
public class UserDAOImpl implements UserDAO{

	public void delet() {
		// TODO Auto-generated method stub
		System.out.println("删除记录成功");
	}

	public void insert() {
		// TODO Auto-generated method stub
		System.out.println("插入记录成功");
	}
}

package com.cvice.dao;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * @author Administrator
 * 
 */

public class DaoFactory {
	
	private static UserDAO userDao = null;//DAO层用户接口对象
	private static DaoFactory instance = new DaoFactory();
	private static Properties pro;//配置文件对象

	private DaoFactory() {
		try {
			//初始化配置文件
			pro = new Properties();
			//采用类加载器方法读取配置文件信息到字节流对象,采用类加载灵活,不用写死
			InputStream inputStream = DaoFactory.class.getClassLoader()
					.getResourceAsStream("db.properties");
			//加载字节流对象
			pro.load(inputStream);
		} catch (IOException e) {
			throw new ExceptionInInitializerError(e);
		}
	}

	/**
	 * 单例模式获取唯一实例
	 * @return
	 */
	public static DaoFactory getInstance() { 
		return instance;
	}

	/**
	 * 根据配置文件的名字获取类的名字,采用反射机制获取其对象
	 * @param Key
	 * @return
	 */
	public UserDAO getUserDAO(String Key) {
		try {
			String className=(String) pro.get(Key);
			userDao = (UserDAO) Class.forName(className).newInstance();
		} catch (InstantiationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return userDao;
	}
}

package com.cvicse.Test;

import com.cvice.dao.DaoFactory;
import com.cvice.dao.UserDAO;

/**
 * @author Administrator
 *
 */
public class DAOTest {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		UserDAO userDao=DaoFactory.getInstance().getUserDAO("userDao");
		userDao.delet();
	}

}

 目录结构


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值