反射+抽象工厂

现在SportsEquipmentFactory使用反射,不用switch判断

代码与上篇文章“抽象工厂模式”类似,只改动了SportsEquipmentFactory的代码

SportsEquipmentFactory

package com.maggie.FactoryMethod;

import java.lang.reflect.InvocationTargetException;

public  class SportsEquipmentFactory {
    
    private String style;
    
    public Ball createBall() throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException, ClassNotFoundException {
         if (style != null && !style.equals("" )) {
            
            String className = "com.maggie.FactoryMethod." + style +"Ball" ;
             // 构造函数需要参数 
            Ball ball = (Ball) Class.forName(className).getConstructor(String. class ).newInstance(style);
             return ball;
        }
        return  null ;
    }
    
    public Sneakers createSneakers() throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException, ClassNotFoundException{
         if (style != null && !style.equals("" )) {
            String className = "com.maggie.FactoryMethod." + style +"Sneakers" ;
            Sneakers sneakers = (Sneakers) Class.forName(className).getConstructor(String. class ).newInstance(style);
             return sneakers;
        }
        return  null ;
    }

    public String getStyle() {
         return style;
    }

    public  void setStyle(String style) {
         this .style = style;
    }
}

 

client端的调用

@Test
     public  void test() throws IOException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException, ClassNotFoundException {
        Properties proper = new Properties();
        InputStream is = this .getClass().getClassLoader().getResourceAsStream("my.properties"); // 在src目录下创建一个my.properties的配置文件,内容为style=foot 
        proper.load(is);
        String style = proper.getProperty("style" );
        
        SportsEquipmentFactory factory = new SportsEquipmentFactory();
        factory.setStyle(style);
        
        Ball ball = factory.createBall();
        ball.play();
        
        Sneakers sneakers = factory.createSneakers();
        sneakers.show();
    }

输出

the ball's color is Foot,I am FootBall
the sneakers is Foot

 

思考:如果业务又做大,工厂又需要生产网球类的产品

使用了反射,就只需要添加网球类和网球鞋类,然后配置文件改个单词就可以,不用去更改工厂类的任何代码,去除了switch和if解决了分支判断带来的耦合,就不违反了开放-封闭原则

 

posted @ 2017-09-21 11:23  七月蜀葵  阅读(256)  评论(0编辑  收藏  举报