Java反射研究(3)


十一、工厂设计模式


1.最简单的工厂设计模式


场景:有一个Fruit接口,Apple类和Orange类都实现了Fruit接口,Factory用来生产水果;

import java.io.*;
import java.util.*;

interface Fruit{
	public void eat();
}
class Apple implements Fruit{
	public void eat(){
		System.out.println("吃苹果");
	}
}
class Orange implements Fruit{
	public void eat(){
		System.out.println("吃橘子");
	}
}
class Factory{
	public static Fruit getInstance(String name)throws Exception{
		Fruit f = null;
		if("apple".equals(name)){
			f = new Apple();
		}
		else if("orange".equals(name)){
			f = new Orange();
		}
		if(f!=null){
			return f;
		}
		else return null;
	}
}
public class FactoryDemo01{
	public static void main(String args[])throws Exception{
		
		Fruit f = Factory.getInstance("apple");
		f.eat();
	}
}

2.通过反射实现


上面的例子有一个坏处,就是在Factory的getInstance代码会随着水果数量增加而增加,比如如果增加了一个banana类,则需要添加

if(name.equals("banana")){...}

这样非常不方便,因此反射就是一个很好的解决方法:

import java.io.*;
import java.util.*;

interface Fruit{
	public void eat();
}
class Apple implements Fruit{
	public void eat(){
		System.out.println("吃苹果");
	}
}
class Orange implements Fruit{
	public void eat(){
		System.out.println("吃橘子");
	}
}
class Factory{
	public static Fruit getInstance(String name)throws Exception{
		Fruit f = null
		Fruit f = (Fruit)Class.forName(name).newInstance();
		if(f!=null){
			return f;
		}
		else return null;
	}
}
public class FactoryDemo01{
	public static void main(String args[])throws Exception{
		
		Fruit f = Factory.getInstance("Apple");
		f.eat();
	}
}

3.增加灵活性:配置文件


但是还有一个缺点,就是如果Apple类等有包名,则如果要访问此类,必须添加包名+类名称才可以。比如Apple类的最上方:package org;则必须通过org.Apple才可以访问Apple类。因此通过Properties文件可以解决这个问题;


import java.io.*;
import java.util.*;

interface Fruit{
	public void eat();
}
class Apple implements Fruit{
	public void eat(){
		System.out.println("吃苹果");
	}
}
class Orange implements Fruit{
	public void eat(){
		System.out.println("吃橘子");
	}
}
class Factory{
	public static Fruit getInstance(String name)throws Exception{
		Fruit f = null
		Fruit f = (Fruit)Class.forName(name).newInstance();
		if(f!=null){
			return f;
		}
		else return null;
	}
        private Factory(){}
}
public class FactoryDemo01{
	public static void main(String args[])throws Exception{
		Properties p = new Properties();
		p.load(new FileInputStream("1.properties"));
		String str = p.getProperty("apple");
		Fruit f = Factory.getInstance(str);
		f.eat();
	}
}
1.properties代码:
apple=Apple
orange=Orange



你可能感兴趣的:(java反射)