`
yidongkaifa
  • 浏览: 4061463 次
文章分类
社区版块
存档分类
最新评论

工厂模式

 
阅读更多

概念:把产品创建过程的细节封装在工厂里的模式

优点:增加产品时抽象工厂不会改变,只要增加相应产品的实现工厂即可,提高了扩展性。

场景:适应单一系列产品的创建

简单工厂只是抽象工厂的一个特例:


fruit.properties文件:

apple = com.cn.test3.Apple
orange = com.cn.test3.Orange



Factory3类工厂文件:


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 className){
Fruit fruit = null;
try {
/*
* 采用Class.forName(className).newInstance()反射技术
* */
fruit = (Fruit)Class.forName(className).newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return fruit;
}
}
class Init{
/*
* 读取properties配置文件
* */
public static Properties getProperty(){
Properties property = new Properties();
File file = new File("E:\\myEclipseSpace\\testFactory\\bin\\com\\cn\\test3\\fruit.properties");
try {
if(file.exists()){
property.load(new FileInputStream(file));
}else{
property.setProperty("apple", "com.cn.test3.Apple");
property.setProperty("orange", "com.cn.test3.Orange");
property.store(new FileOutputStream(file), "fruit class");
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return property;
}
}
public class Factory3{
public static void main(String args[]){
Properties property = Init.getProperty();
Fruit f = Factory.getInstance(property.getProperty("apple"));
if(f != null){
f.eat();
}
}
}



分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics