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


    //产品接口
    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();
    	}
    	
    }
    

      

  • 相关阅读:
    正则表达式
    浏览器加载时间线
    浏览器事件
    脚本化CSS
    定时器元素大小位置属性等 20181231
    关于行内元素 20181229
    个人冲刺01
    周总结
    团队冲刺10
    团队冲刺09
  • 原文地址:https://www.cnblogs.com/chenweichu/p/6343541.html
Copyright © 2020-2023  润新知