简单工厂模式,利用反射机制让简单工厂模式变得更灵活

 

//产品接口
package com.wch.project;

public interface HairInterface {
	
	public void draw();
	
}


//产品类
package com.wch.project;

public class LeftHair implements HairInterface{

	@Override
	public void draw() {
		// TODO Auto-generated method stub
		System.out.println("-----------------左偏分----------------");
	}

}


//产品类
package com.wch.project;

public class RightHair implements HairInterface {

	@Override
	public void draw() {
		// TODO Auto-generated method stub
		System.out.println("-----------------右偏分----------------");
	}

}


//工厂
package com.wch.project;

public class HairFactory {

	//第一种:简单工厂
	public HairInterface getHair(String hair){
		if("left".equals(hair)){
			return new LeftHair();
		}else if("right".equals(hair)){
			return new RightHair();
		}
		return null;
	}
	
	//第二种:简单工厂- 反射机制(1.className需要传完整类路径。2.className可以用键值对形式存取,方便客户端调用。)
	public HairInterface getHairByClass(String className){
		try {
			HairInterface hair = (HairInterface)Class.forName(className).newInstance();
			return hair;
		} 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 null;
	}

}


//客户端调用
package com.wch.project;

public class WchTest {

	public static void main(String[] args) throws Exception{
		//第一种调用
		/*HairFactory hairFactory = new HairFactory();
		HairInterface hair = hairFactory.getHair("left");
		hair.draw();*/
		
		//第二种调用
		HairFactory hairFactory = new HairFactory();
		HairInterface hair = hairFactory.getHairByClass("com.wch.project.RightHair");  // right -> com.wch.project.RightHair
		hair.draw();
	}
	
}

  

posted @ 2017-01-23 11:01  N神3  阅读(475)  评论(0编辑  收藏  举报