简单工厂模式
简单工厂的本质是:选择实现(用户不需要知道具体的实现类的信息,只需要调用接口使用即可。)
代码目录:
Api.java:
[java]
package a;
public interface Api {
public void test1(String s);
}
package a;
public interface Api {
public void test1(String s);
}
Client.java:
[java]
package a;
public class Client {
public static void main(String[] args){
Api api=Factory.createApi();
api.test1("ggggg");
}
}
package a;
public class Client {
public static void main(String[] args){
Api api=Factory.createApi();
api.test1("ggggg");
}
}
Impl.java:
[java]
package a;
public class Impl implements Api{
public void test1(String s){
System.out.println("impl1 is "+s);
}
}
package a;
public class Impl implements Api{
public void test1(String s){
System.out.println("impl1 is "+s);
}
}
Factory.java:()
[java]
package a;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
<SPAN style="COLOR: #ff0000">//工厂类,用来创建Api对象</SPAN>
public class Factory {
public static Api createApi(){
<SPAN style="COLOR: #ff0000"> //直接读取配置文件来获取需要创建实例的类</SPAN>
Properties p=new Properties();
InputStream in =null;
try{
in=Factory.class.getResourceAsStream("FactoryTest.properties");
p.load(in);
}catch (IOException e){
System.out.println("error");
e.printStackTrace();
}finally{
try{
in.close();
}catch (IOException e){
e.printStackTrace();
}
}
<SPAN style="COLOR: #ff0000"> //用反射去创建</SPAN>
Api api=null;
try{
api=(Api)Class.forName(p.getProperty("ImplClass")).newInstance();
}catch (InstantiationException e){
e.printStackTrace();
}catch (IllegalAccessException e){
e.printStackTrace();
}catch(ClassNotFoundException e){
e.printStackTrace();
}
return api;
}
}
package a;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
//工厂类,用来创建Api对象
public class Factory {
public static Api createApi(){
//直接读取配置文件来获取需要创建实例的类
Properties p=new Properties();
InputStream in =null;
try{
in=Factory.class.getResourceAsStream("FactoryTest.properties");
p.load(in);
}catch (IOException e){
System.out.println("error");
e.printStackTrace();
}finally{
try{
in.close();
}catch (IOException e){
e.printStackTrace();
}
}
//用反射去创建
Api api=null;
try{
api=(Api)Class.forName(p.getProperty("ImplClass")).newInstance();
}catch (InstantiationException e){
e.printStackTrace();
}catch (IllegalAccessException e){
e.printStackTrace();
}catch(ClassNotFoundException e){
e.printStackTrace();
}
return api;
}
}
FactoryTest.properties:(配置文件,添加新类的时候,只需要更改配置文件即可,其他程序都不需要改动。)
[plain]
ImplClass=a.Impl
ImplClass=a.Impl
运行结果:
[plain]
impl1 is ggggg
impl1 is ggggg
补充:软件开发 , Java ,