工厂方法模式应用场景:
1.当有一组类型的对象需要创建
2.编码时,不能预见需创建哪种类型的实例
3.考虑程序的可扩展性
代码结构:
例如:画一个人的头像,头像分为左偏分发型、右偏分发型、以及中分等。
1).创建一个接口,里面有一个函数draw()
public interface HairInterface { public void draw(); }
2).实现类
左偏分:
public class LeftHair implements HairInterface { public void draw(){ System. out.println("=======左偏分=======" ); } }
右偏分:
public class RightHair implements HairInterface { public void draw(){ System. out.println("=======右偏分=======" ); } }
3).创建一个工厂来获取类的实例,而不是通过new的方式,从而达到解耦合的效果
(根据具体的类名来创建实例,这也叫java的反射机制)
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(); } }
如此,一个简单工厂模式就创立成功了
如果因为需要写绝对路径来获取类名比较麻烦可以通过properties文件映射,如下:
1.创建一个properties 文件,命名为name.properties:
left=com.sunny.project.LeftHair;
right=com.sunny.project.RightHair;
2.创建一个PropertiesReader读取文件
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();