Spring(二)工厂模式+反射+配置文件
(1)简单的工厂模式:
简单工场模式就是把对象的创建交给工厂来管理,
在工厂类中的工厂方法中编写好处理代码,
根据接收到的参数值来创建对应的对象,这就是简单工厂模式。
代码:
public class ShapeFactory { //使用 getShape 方法获取形状类型的对象 public Shape getShape(String shapeType){ if(shapeType == null){ return null; } if(shapeType.equalsIgnoreCase("CIRCLE")){ return new Circle(); } else if(shapeType.equalsIgnoreCase("RECTANGLE")){ return new Rectangle(); } else if(shapeType.equalsIgnoreCase("SQUARE")){ return new Square(); } return null; } }
(2)配置文件和反射机制来编码:
虽然对象和对象调用者没有产生耦合,但是却和工厂类产生了耦合,
而spring最大的亮点之一就是解耦合,这里修改方法使用配置文件和反射机制来编码。
先写出Shape接口和Shape的继承类:
//Shape.java 接口 public interface Shape { void draw(); } //Circle.java 继承类 public class Circle implements Shape { @Override public void draw() { System.out.println("Inside Circle::draw() method."); } } //Square.java 继承类 public class Square implements Shape { @Override public void draw() { System.out.println("Inside Square::draw() method."); } } //Rectangle.java 继承类 public class Rectangle implements Shape { @Override public void draw() { System.out.println("Inside Rectangle::draw() method."); } }
接着写配置文件内容:
## conf.properties circle=yc.wsrgan.shape.Circle rectangle=yc.wsrgan.shape.Rectangle square=yc.wsrgan.shape.Square
接着:修改ShapeFactory类,使用配置文件和反射机制
public class ShapeFactory { public Shape getShape(String shapeType) { Shape shape = null; Properties prop = new Properties(); InputStream is = null; try { is = ShapeFactory.class.getResourceAsStream("/conf.properties"); prop.load(is); } catch (Exception e) { e.printStackTrace(); } finally { try { is.close(); } catch (Exception e2) { e2.printStackTrace(); } } try { Class<?> clazz = Class.forName(prop.getProperty(shapeType)); shape = (Shape) clazz.newInstance(); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } return shape; } }
解释:
Class c = Class.forName(“A”);factory = (AInterface)c.newInstance();
其中AInterface是A的接口,拆成下面这样写:
String className = "A";Class c = Class.forName(className);factory = (AInterface)c.newInstance();
进一步写:
String className = readfromXMlConfig;//从xml 配置文件中获得字符串
Class c = Class.forName(className);
factory = (AInterface)c.newInstance();
上面代码就消灭了A类名称,优点:无论A类怎么变化,上述代码不变,甚至可以更换A的兄弟类B , C , D....等,
只要他们继承Ainterface就可以。
(3)为什么改成这种模式?

浙公网安备 33010602011771号