java通过反射机制实现工厂设计模式

原始设计模式:
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() ;
		}
	}
};
但是以上代码存在问题,因为每次增加实现类,都需要修改Factory类。所以我们需要用反射机制实现。
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].mldn视频

转载于:https://my.oschina.net/itfanr/blog/358408

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值