反射+抽象工厂

Posted 七月蜀葵

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了反射+抽象工厂相关的知识,希望对你有一定的参考价值。

现在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解决了分支判断带来的耦合,就不违反了开放-封闭原则

 

以上是关于反射+抽象工厂的主要内容,如果未能解决你的问题,请参考以下文章

抽象工厂模式(JAVA反射)

14抽象工厂获取数据访问层的实例,缓存的使用和反射的使用

简单工厂抽象工厂反射工厂

一抽象工厂模式&&简单工厂+反射改进抽象工厂

反射+配置文件+抽象工厂

测开之路十八:反射与抽象工厂