JAVA 设计模式之Factory
工厂模式定义:提供创建对象的接口。为什么工厂模式是如此常用?因为工厂模式就相当于创建实例对象的new,我们经常要根据类Class生成实例对象,如A a=new A() 工厂模式也是用来创建实例对象的,所以以后new时就要多个心眼,是否可以考虑实用工厂模式,虽然这样做,可能多做一些工作,但会给你系统带来更大的可扩展性和尽量少的修改量。
这里用一个简单例子说明:
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Properties;
public class Test{
public static void main(String[] args) throws Exception{
int i = System.in.read();
Vehicle ve = null;
ve = new Factory().build(i);
ve.move();
}
}
//交通工具接口
interface Vehicle{
public void move();
}
class Bike implements Vehicle{
public void move(){
System.out.println("Bike !");
}
}
class Car implements Vehicle{
public void move(){
System.out.println("Car !");
}
}
//生产对象的工厂
class Factory{
public Vehicle build(int i) throws Exception{
i = i - 48;
String key = i +"";
String className = new Prop().readValue(key);
Vehicle ve = null;
ve = (Vehicle)Class.forName(className).newInstance();
return ve;
}
}
//配置文件
class Prop{
public String readValue(String key)throws Exception{
Properties pro = new Properties();
InputStream in = new BufferedInputStream(new FileInputStream("C:\\info.properties"));
pro.load(in);
String value = pro.getProperty(key);
return value;
}
}
补充:
info.properties内容
1=Bike
2=Car
页:
[1]