反射+抽象工厂

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

 

转载于:https://www.cnblogs.com/maggiejyt/p/7567660.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值