基于Spring注解实现的工厂模式

本文转自oschina南寒之星的博文,原文链接如下:https://my.oschina.net/u/923324/blog/832269

摘要: 工厂模式是大家熟知的一种设计模式,在spring BeanFactory将这模式运用自如。 前面讲过如果通过xml配置的方式实现,今天我们来讲讲如何通过注解的方式实现工厂模式。 主要思路 1. 扫描classPath下的的类,将这些class存储到setmap中 2. 遍历set中的class,找出被自定义facory注解注解过的的class,以beanId,class的对象形式封装到一个map集合里 3. 暴露一个方法getBean,通过beanId查找对于的class的对象,匹配成功后返回该对象


[2017-5-16 by Daniel] 今天发现了更简单的方法,请见本人的这篇文章《基于Spring注解实现工厂模式》。


工厂模式是大家熟知的一种设计模式,在spring BeanFactory将这模式运用自如。 前面讲过如果通过xml配置的方式实现,今天我们来讲讲如何通过注解的方式实现工厂模式。 主要思路

  1. 扫描classPath下的的类,将这些class存储到setmap中
  2. 遍历set中的class,找出被自定义facory注解注解过的的class,以beanId,class的对象形式封装到一个map集合里
  3. 暴露一个方法getBean,通过beanId查找对于的class的对象,匹配成功后返回该对象

同样回顾下常见的简单工厂写法

创建一个接口类Pizza


public interface Pizza{
    public float getPrice();
}

MargheritaPizza 类


public class MargheritaPizza implements Pizza{
    public float getPrice() {
        System.out.println("8.5f");
        return 8.5f;

    }
}

CalzonePizza 类


public class CalzonePizza implements Pizza{
    public float getPrice() {
        System.out.println("2.5f");
        return 2.5f;
    }


}

建立工厂类PizzaFactory

通过传入参数id,选择不同的实例类,如果后续不断的增加新类,会频繁的修改create方法,不符合开闭原则


public interface Pizza{
    public float getPrice();
}

MargheritaPizza 类


public class MargheritaPizza implements Pizza{
    public float getPrice() {
        System.out.println("8.5f");
        return 8.5f;

    }
}

CalzonePizza 类


public class CalzonePizza implements Pizza{
    public float getPrice() {
        System.out.println("2.5f");
        return 2.5f;
    }


}

建立工厂类PizzaFactory

通过传入参数id,选择不同的实例类,如果后续不断的增加新类,会频繁的修改create方法,不符合开闭原则


public class PizzaFactory {
    public Pizza create(String id) {
        if (id == null) {
          throw new IllegalArgumentException("id is null!");
        }
        if ("Calzone".equals(id)) {
          return new CalzonePizza();
        }

        if ("Margherita".equals(id)) {
          return new MargheritaPizza();
        }

        throw new IllegalArgumentException("Unknown id = " + id);
      }

}

使用annotation注解方式

注解方式减少对代码的侵入,避免xml配置的繁琐,是spring高版喜欢使用的方式

创建ClassPathSpringScanner 扫描类

获取当前classLoad下的所有class文件


public class ClassPathSpringScanner {


    public static final String CLASS_SUFFIX = ".class";

    private ClassLoader classLoader = getClass().getClassLoader();


    public Set<Class<?>> getClassFile(String packageName) throws IOException {

        Map<String, String> classMap = new HashMap<>(32);
        String path = packageName.replace(".", "/");
        /**
         * 通过classLoader加载文件,循环遍历文件,转换class文件
         */
        Enumeration<URL> urls = classLoader.getResources(path);

        while (urls!=null && urls.hasMoreElements()) {
            URL url = urls.nextElement();
            String protocol = url.getProtocol();
            /**
             * 如果是文件
             */
            if ("file".equals(protocol)) {
                String file = URLDecoder.decode(url.getFile(), "UTF-8");
                File dir = new File(file);
                if(dir.isDirectory()){
                    parseClassFile(dir, classMap);
                }else {
                    throw new IllegalArgumentException("file must be directory");
                }
            } 
        }

        Set<Class<?>> set = new HashSet<>(classMap.size());
        for(String key : classMap.keySet()){
            String className = classMap.get(key);
            try {
                set.add(getClass().forName(className));
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        }
        return set;
    }

    /**
     * 递归算法把class封装到map集合里
     * @param dir
     * @param packageName
     * @param classMap
     */
    protected void parseClassFile(File dir, Map<String, String> classMap){
        if(dir.isDirectory()){
            File[] files = dir.listFiles();
            for (File file : files) {
                parseClassFile(file, classMap);
            }
        } else if(dir.getName().endsWith(CLASS_SUFFIX)) {
            String name = dir.getPath();
            name = name.substring(name.indexOf("classes")+8).replace("\\", ".");
            addToClassMap(name, classMap);
        }
    }



    private boolean addToClassMap(String name, Map<String, String> classMap){
        if(!classMap.containsKey(name)){
            classMap.put(name, name.substring(0, name.length()-6)); //去掉.class
        }
        return true;
    }

自定义工厂注解@Factory

只要被Factory注解过的类,都能通过beanId实例化对象。

@Target(ElementType.TYPE) 
@Retention(RetentionPolicy.RUNTIME)
public @interface Factory {

    /**
     * 用来表示对象的唯一id
     */
    String id();
}

创建 BeanFactory 接口

public interface BeanFactory {
    public Object getBean(String id);
}

创建BeanFactory 的实现类AnnApplicationContext

将扫描后得到的class封装到一个map里,找出有被Factory注解的类,以beanId,class对象的键值对形式存储。

public class AnnApplicationContext implements BeanFactory{



    private Map<String, Object> factoryClasses = new LinkedHashMap<String, Object>();

    private Set<Class<?>> classSet = new HashSet();


    ClassPathSpringScanner scanner = new ClassPathSpringScanner();
    /*
     * 构造函数初始化扫描获取所有类
     */
    public AnnApplicationContext(String packageName) {

        try {
            //扫描classPath下的所有类,并返回set
            classSet = scanner.getClassFile(packageName);

            /**
             * 遍历所有类,找出有factory注解的类,并封装到linkedHashMap里
             */
            for (Class<?> cls : classSet){
                Factory factory = (Factory) cls.getAnnotation(Factory.class);
                if(factory != null) 
                try {
                    factoryClasses.put(factory.id(), cls.newInstance());
                } catch (InstantiationException | IllegalAccessException e) {
                    e.printStackTrace();
                }

            }
        } catch (IOException e) {
            e.printStackTrace();
        }  
    }


    /**
     * 输入的id,对应到factoryGroupedClasses的关系,实例化工厂对象
     * @param beanId
     * @return
     */
    @Override
    public Object getBean(String id) {

        return factoryClasses.get(id);
    }

MargheritaPizza 类

添加注释Factory,定义beanId:Margherita

@Factory(id = "margherita")
public class MargheritaPizza implements Pizza{
    public float getPrice() {
        System.out.println("8.5f");
        return 8.5f;

    }
}

CalzonePizza 类

添加注释Factory,定义beanId:Calzone

@Factory(id = "calzone")
public class CalzonePizza implements Pizza{
    public float getPrice() {
        System.out.println("2.5f");
        return 2.5f;
    }


}

测试下

public static void main(String[] args) {
        /**
         * 扫描com.annotation.factory下的类
         */
        AnnApplicationContext factoryProcessor = new AnnApplicationContext("com.annotation.factory.spring");
        Pizza p= (Pizza) factoryProcessor.getBean("Calzone");
        p.getPrice();

    }

好了,看完代码应该很清楚了,注解是不是给我们带来很多方便了。 留个思考题,如何默认通过类的名字,首个字母小写来作为beanId



public interface Pizza{
    public float getPrice();
}

MargheritaPizza 类


public class MargheritaPizza implements Pizza{
    public float getPrice() {
        System.out.println("8.5f");
        return 8.5f;

    }
}

CalzonePizza 类


public class CalzonePizza implements Pizza{
    public float getPrice() {
        System.out.println("2.5f");
        return 2.5f;
    }


}

建立工厂类PizzaFactory

通过传入参数id,选择不同的实例类,如果后续不断的增加新类,会频繁的修改create方法,不符合开闭原则


public class PizzaFactory {
    public Pizza create(String id) {
        if (id == null) {
          throw new IllegalArgumentException("id is null!");
        }
        if ("Calzone".equals(id)) {
          return new CalzonePizza();
        }

        if ("Margherita".equals(id)) {
          return new MargheritaPizza();
        }

        throw new IllegalArgumentException("Unknown id = " + id);
      }

}

使用annotation注解方式

注解方式减少对代码的侵入,避免xml配置的繁琐,是spring高版喜欢使用的方式

创建ClassPathSpringScanner 扫描类

获取当前classLoad下的所有class文件


public class ClassPathSpringScanner {


    public static final String CLASS_SUFFIX = ".class";

    private ClassLoader classLoader = getClass().getClassLoader();


    public Set<Class<?>> getClassFile(String packageName) throws IOException {

        Map<String, String> classMap = new HashMap<>(32);
        String path = packageName.replace(".", "/");
        /**
         * 通过classLoader加载文件,循环遍历文件,转换class文件
         */
        Enumeration<URL> urls = classLoader.getResources(path);

        while (urls!=null && urls.hasMoreElements()) {
            URL url = urls.nextElement();
            String protocol = url.getProtocol();
            /**
             * 如果是文件
             */
            if ("file".equals(protocol)) {
                String file = URLDecoder.decode(url.getFile(), "UTF-8");
                File dir = new File(file);
                if(dir.isDirectory()){
                    parseClassFile(dir, classMap);
                }else {
                    throw new IllegalArgumentException("file must be directory");
                }
            } 
        }

        Set<Class<?>> set = new HashSet<>(classMap.size());
        for(String key : classMap.keySet()){
            String className = classMap.get(key);
            try {
                set.add(getClass().forName(className));
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        }
        return set;
    }

    /**
     * 递归算法把class封装到map集合里
     * @param dir
     * @param packageName
     * @param classMap
     */
    protected void parseClassFile(File dir, Map<String, String> classMap){
        if(dir.isDirectory()){
            File[] files = dir.listFiles();
            for (File file : files) {
                parseClassFile(file, classMap);
            }
        } else if(dir.getName().endsWith(CLASS_SUFFIX)) {
            String name = dir.getPath();
            name = name.substring(name.indexOf("classes")+8).replace("\\", ".");
            addToClassMap(name, classMap);
        }
    }



    private boolean addToClassMap(String name, Map<String, String> classMap){
        if(!classMap.containsKey(name)){
            classMap.put(name, name.substring(0, name.length()-6)); //去掉.class
        }
        return true;
    }

自定义工厂注解@Factory

只要被Factory注解过的类,都能通过beanId实例化对象。

@Target(ElementType.TYPE) 
@Retention(RetentionPolicy.RUNTIME)
public @interface Factory {

    /**
     * 用来表示对象的唯一id
     */
    String id();
}

创建 BeanFactory 接口

public interface BeanFactory {
    public Object getBean(String id);
}

创建BeanFactory 的实现类AnnApplicationContext

将扫描后得到的class封装到一个map里,找出有被Factory注解的类,以beanId,class对象的键值对形式存储。

public class AnnApplicationContext implements BeanFactory{



    private Map<String, Object> factoryClasses = new LinkedHashMap<String, Object>();

    private Set<Class<?>> classSet = new HashSet();


    ClassPathSpringScanner scanner = new ClassPathSpringScanner();
    /*
     * 构造函数初始化扫描获取所有类
     */
    public AnnApplicationContext(String packageName) {

        try {
            //扫描classPath下的所有类,并返回set
            classSet = scanner.getClassFile(packageName);

            /**
             * 遍历所有类,找出有factory注解的类,并封装到linkedHashMap里
             */
            for (Class<?> cls : classSet){
                Factory factory = (Factory) cls.getAnnotation(Factory.class);
                if(factory != null) 
                try {
                    factoryClasses.put(factory.id(), cls.newInstance());
                } catch (InstantiationException | IllegalAccessException e) {
                    e.printStackTrace();
                }

            }
        } catch (IOException e) {
            e.printStackTrace();
        }  
    }


    /**
     * 输入的id,对应到factoryGroupedClasses的关系,实例化工厂对象
     * @param beanId
     * @return
     */
    @Override
    public Object getBean(String id) {

        return factoryClasses.get(id);
    }

MargheritaPizza 类

添加注释Factory,定义beanId:Margherita

@Factory(id = "margherita")
public class MargheritaPizza implements Pizza{
    public float getPrice() {
        System.out.println("8.5f");
        return 8.5f;

    }
}

CalzonePizza 类

添加注释Factory,定义beanId:Calzone

@Factory(id = "calzone")
public class CalzonePizza implements Pizza{
    public float getPrice() {
        System.out.println("2.5f");
        return 2.5f;
    }


}

测试下

public static void main(String[] args) {
        /**
         * 扫描com.annotation.factory下的类
         */
        AnnApplicationContext factoryProcessor = new AnnApplicationContext("com.annotation.factory.spring");
        Pizza p= (Pizza) factoryProcessor.getBean("Calzone");
        p.getPrice();

    }

好了,看完代码应该很清楚了,注解是不是给我们带来很多方便了。 留个思考题,如何默认通过类的名字,首个字母小写来作为beanId

  • 4
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值