简单工厂设计模式理解

package factory.f3;

public interface Api {
	public void operate(String s);
	

}
  package factory.f3;
public class ApiImplB implements Api {

	public void operate(String s) {
		// TODO Auto-generated method stub
System.out.println("ApiImplB s=="+s);
	}

}

 package factory.f3;

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

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){
		e.printStackTrace();
	}
	//反射
	Api api= null;
		
	try {
		
		
		api=(Api)Class.forName(p.getProperty("ImplClass")).newInstance();
		
		
	} catch (InstantiationException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	} catch (IllegalAccessException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	} catch (ClassNotFoundException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
		
		

		
	return api;
}}

 package factory.f3;

public class Test {
	public static void main(String args[]){
	Api api=factory.createApi();
	api.operate("good");
	}
}

 factoryTest.properties

 

ImplClass=factory.f3.ApiImplB

你可能感兴趣的:(java,设计模式)