您的位置:首页 > 其它

工厂设计模式

2015-10-03 13:12 465 查看
工厂设计模式最大的好处是可以在应用进行解耦合操作
package org.lxh.demo15.factorydemo01;
interface Fruit
{
public void eat();  //吃水果
}
class Apple implements Fruit
{
public void eat(){  //覆写eat()方法

System.out.println("**吃苹果");
}
}
class Orange implements Fruit
{
public void eat(){

System.out.println("**吃橘子");
}
}
class Factory
{
public static Fruit getInstance(String className){

Fruit fruit =null;
try{

fruit=(Fruit)Class.forName(className).newInstance();
}catch(Exception e){

e.printStackTrace();
}
return fruit;
}
}
public class FactoryDemo01
{
public static void main(String args[]){

Fruit f=Factory.getInstance("org.lxh.demo15.factorydemo01.Apple");
if(f!=null){

f.eat();
}
}
}

    以上确实在扩充子类的时候可以不用去修改工厂类,但是以上的程序代码中依然会存在问题,毕竟,

在使用的时候如果输入完整的“包.类”名称的话,肯定很麻烦,所以,此时,可以通过一些配置文件的

方式保存这些完整的类路径。

结合属性文件的工厂模式:

以上的操作代码虽然可以通过反射取得接口的实例,但是在操作的时候需要传入完整的包.类名称,

而且用户也无法知道一个接口有多少个可以使用的子类,所以此时可以通过属性文件的形式配置

所要的子类信息。



fruit.propertiers:

apple=org.lxh.demo15.factorydemo02.Apple

orange=org.lxh.demo15.factorydemo02.Orange

程序运行的时候,就可以将属性文件的内容读取出来,之后直接操作属性文件中的key,

就可以避免输入过长的类路路径。

package org.lxh.demo15.factorydemo02 ;
import java.util.Properties ;
import java.io.File ;
import java.io.FileOutputStream ;
import java.io.FileInputStream ;
interface Fruit{
public void eat() ; // 吃水果
}
class Apple implements Fruit{
public void eat(){ // 覆写eat()方法
System.out.println("** 吃苹果");
}
};
class Orange implements Fruit{
public void eat(){
System.out.println("** 吃橘子") ;
}
};
class Init{
public static Properties getPro(){
Properties pro = new Properties() ;
File f = new File("d:\\fruit.properties") ; // 找到属性文件
try{
if(f.exists()){ // 文件存在
pro.load(new FileInputStream(f)) ; // 读取属性
}else{
pro.setProperty("apple","org.lxh.demo15.factorydemo02.Apple") ;
pro.setProperty("orange","org.lxh.demo15.factorydemo02.Orange") ;
pro.store(new FileOutputStream(f),"FRUIT CLASS") ;
}
}catch(Exception e){}
return pro ;
}
};
class Factory{
public static Fruit getInstance(String className){
Fruit fruit = null ;
try{
fruit = (Fruit)Class.forName(className).newInstance() ;
}catch(Exception e){
e.printStackTrace() ;
}
return fruit ;
}
};
public class FactoryDemo02{
public static void main(String args[]){
Properties pro = Init.getPro() ;
Fruit f = Factory.getInstance(pro.getProperty("apple")) ;
if(f!=null){
f.eat() ;
}
}
};     以上的程序达到了配置文件与程序代码相分离的目的,那么这种设计思路是以后开发的基本思路,
当然,最新的设计理念:是在程序中直接通过注释的方式进行配置。

总结:

1.反射机制对程序开发所带来的好处

2.程序代码与配置文件相分离的理论
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: