简单工厂模式(有待优化,大家多提建议)

测试类:

package com.test;



import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;


import com.test.factory.Factory;
import com.test.productImpl.Fruit;


public class Test {


/**
* @param args
* @throws IOException 
* @throws ClassNotFoundException 
* @throws IllegalAccessException 
* @throws InstantiationException 
*/
public static void main(String[] args) throws IOException, InstantiationException, IllegalAccessException, ClassNotFoundException {
Properties pro = new Properties();
InputStream in = new FileInputStream("src/com/test/pro.properties" );
pro.load(in);
String str = pro.getProperty("apple");
Factory fac = new Factory();
Fruit f = fac.createFruit(str);
f.display();
}

}

配置文件:

apple=com.test.productImpl.Apple
orange=com.test.productImpl.Orange
banana=com.test.productImpl.Banana

产品类

package com.test.productImpl;


public class Banana  implements Fruit {
public void display() {
System.out.println("Banana");
}
}

package com.test.productImpl;


public class Apple implements Fruit {
public void display() {
// TODO Auto-generated method stub
System.out.println("apple");
}
}


package com.test.productImpl;

public interface Fruit {
public abstract void display();
}


package com.test.productImpl;
public class Orange  implements Fruit {
public void display() {
System.out.println("orange");
}
}

工厂类

package com.test.factory;


import com.test.productImpl.Fruit;


public class Factory {
public Fruit createFruit(String type) throws InstantiationException, IllegalAccessException, ClassNotFoundException
{
Fruit f = null;
f = (Fruit)Class.forName(type).newInstance();
return f;
}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值