反射在工厂模式中的使用

部分内容来自:https://www.cnblogs.com/lzq198754/p/5780331.html

1反射机制是什么

反射机制是在运行状态中,对于任意一个类,都能够知道这个类的所有属性和方法;对于任意一个对象,都能够调用它的任意一个方法和属性;这种动态获取的信息以及动态调用对象的方法的功能称为java语言的反射机制。

2反射机制能做什么

反射机制主要提供了以下功能: 

  • 在运行时判断任意一个对象所属的类;

  • 在运行时构造任意一个类的对象;

  • 在运行时判断任意一个类所具有的成员变量和方法;

  • 在运行时调用任意一个对象的方法;

  • 生成动态代理

 1 /**
 2  * @Author zhangliwei
 3  * @Date 2018/7/20 下午4:06
 4  */
 5 public class FruitFactory {
 6 
 7     public static Fruit instance (String fruitKindPath){
 8         Fruit fruit = null;
 9         try {
10             fruit = (Fruit) Class.forName(fruitKindPath).newInstance();
11         } catch (Exception e){
12             System.out.println(e.getMessage());
13         }
14 
15         return  fruit;
16     }
17 }
1 /**
2  * @Author zhangliwei
3  * @Date 2018/7/20 下午4:04
4  */
5 public interface Fruit {
6 
7     void eat();
8 }
 1 /**
 2  * @Author zhangliwei
 3  * @Date 2018/7/20 下午4:05
 4  */
 5 public class Apple implements Fruit {
 6     @Override
 7     public void eat() {
 8         System.out.println("Apple eating");
 9     }
10 }
 1 /**
 2  * @Author zhangliwei
 3  * @Date 2018/7/20 下午4:05
 4  */
 5 public class Pench implements Fruit {
 6     @Override
 7     public void eat() {
 8         System.out.println("pench eating");
 9     }
10 }
 1 /**
 2  * @Author zhangliwei
 3  * @Date 2018/7/20 下午4:11
 4  */
 5 public class TestReflect {
 6 
 7     public static void main(String[] args) {
 8         Fruit fruit =  FruitFactory.instance("com.ai.channel.reflectfactory.Apple");
 9 
10         if(null != fruit){
11             fruit.eat();
12         }
13     }
14 }

对于普通的工厂模式当我们在添加一个子类的时候,就需要对应的修改工厂类。 当我们添加很多的子类的时候,会很麻烦。

  Java 工厂模式可以参考上一篇文章
  现在我们利用反射机制实现工厂模式,可以在不修改工厂类的情况下添加任意多个子类。
  但是有一点仍然很麻烦,就是需要知道完整的包名和类名,这里可以使用properties配置文件来完成。
  java 读取 properties 配置文件 的方法可以参考
  http://baike.xsoftlab.net/view/java-read-the-properties-configuration-file

猜你喜欢

转载自www.cnblogs.com/zhangliwei/p/9342209.html