标签:
public interface HairInterface { public void draw(); }
public class LeftHair implements HairInterface { public void draw(){ System. out.println("=======左偏分=======" ); } }
public class RightHair implements HairInterface { public void draw(){ System. out.println("=======右偏分=======" ); } }
public class Hairfactory { public HairInterface getHairByClass(String className) { HairInterface hair; try { hair = (HairInterface) Class.forName(className).newInstance(); return hair; } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } return null ; } }
4).测试类
public class HairTest { public static void main(String[] args) throws Exception { Hairfactory factory = new Hairfactory(); HairInterface hair = factory.getHairByClass("com.sunny.project.LeftHair" );//注意此处为绝对路径 hair.draw(); } }
如此,一个简单工厂模式就创立成功了
left=com.sunny.project.LeftHair;
right=com.sunny.project.RightHair;
public class PropertiesReader { public Map<String,String> getProperties(){ Map<String,String> map = new HashMap<String,String>(); Properties props = new Properties(); try{ InputStream in = getClass().getResourceAsStream("name.properties" ); props.load(in); Enumeration en = props.propertyNames(); while(en.hasMoreElements()){ String key = (String)en.nextElement(); String property = props.getProperty(key); map.put(key, property); } return map; } catch(Exception e){ e.printStackTrace(); } return null ; } }
3.测试类的调用方法:
Map<String,String> map = new PropertiesReader().getProperties(); Hairfactory factory = new Hairfactory(); HairInterface hair = factory.getHairByClass(map.get( "left")); hair.draw();
标签:
原文地址:http://www.cnblogs.com/doudingbest/p/4957159.html