码迷,mamicode.com
首页 > 其他好文 > 详细

反射+抽象工厂

时间:2017-09-21 13:14:32      阅读:138      评论:0      收藏:0      [点我收藏+]

标签:load   oca   ack   配置   .sh   instance   去除   div   nta   

技术分享

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

 

反射+抽象工厂

标签:load   oca   ack   配置   .sh   instance   去除   div   nta   

原文地址:http://www.cnblogs.com/maggiejyt/p/7567660.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!