简单工厂模式(java语言实现)
2015-10-14 21:37
423 查看
1 工厂模式:
百度百科:工厂模式是我们最常用的实例化对象模式了,是用工厂方法代替new操作的一种模式。著名的Jive论坛 ,就大量使用了工厂模式,工厂模式在Java程序系统可以说是随处可见。因为工厂模式就相当于创建实例对象的new,我们经常要根据类Class生成实例对象,如A a=new A() 工厂模式也是用来创建实例对象的,所以以后new时就要多个心眼,是否可以考虑使用工厂模式,虽然这样做,可能多做一些工作,但会给你系统带来更大的可扩展性和尽量少的修改量。
2 简单工厂模式实现
// 工厂模式提供了一个更好的方式来创建对象, // 创建对象而不用暴露创建逻辑,这使得条用工厂得到对象的程序代码更简洁。 创建一个接口 Shape , public interface Shape { void draw(); } Rectangle.java public class Rectangle implements Shape { @Override public void draw() { System.out.println("Inside Rectangle::draw() method."); } } Square.java public class Square implements Shape { @Override public void draw() { System.out.println("Inside Square::draw() method."); } } Circle.java public class Circle implements Shape { @Override public void draw() { System.out.println("Inside Circle::draw() method."); } } // 工厂模式的核心类就是 Factory 类, // 它会根据使用 Factory 的程序传入的字符串的值返回对应的形状对象实例。 public class ShapeFactory { //use getShape method to get object of type shape 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; } } //测试 public class Main { public static void main ae4b (String[] args) { ShapeFactory shapeFactory = new ShapeFactory(); //get an object of Circle and call its draw method. Shape shape1 = shapeFactory.getShape("CIRCLE"); //call draw method of Circle shape1.draw(); //get an object of Rectangle and call its draw method. Shape shape2 = shapeFactory.getShape("RECTANGLE"); //call draw method of Rectangle shape2.draw(); //get an object of Square and call its draw method. Shape shape3 = shapeFactory.getShape("SQUARE"); //call draw method of circle shape3.draw(); } } 输出: Inside Circle::draw() method. Inside Rectangle::draw() method. Inside Square::draw() method.
3 简单工厂模式解析
1 所有的工厂都是用来封装对象的创建2 简单工厂,虽然不是真正的设计模式但是仍不失为一个简单的方法,可以将客户程序从具体类解耦。
3 通过实现 superType 把对象的创建交个子类,子类实现工厂方法创建对象。
相关文章推荐
- struts 2的action中配置result视图结果加反斜杠的注意事项
- 看看Spring源码(二)——bean实例化
- JavaWeb三大组件——过滤器的运行机制理解
- eclipse中导入项目后中文成乱码解决办法
- JAVA多线程实现和应用总结
- java.util.ConcurrentModificationException 解决办法
- Java语法糖4:内部类
- java中三个点的用法
- 马士兵Java课堂笔记-3-Switch循环语句小细节
- springmvc 之 helloworld
- Java求最大公约数和最小公倍数
- java WEB开发 找回密码 如何通过注册时候的邮箱找回(修改)密码
- java记——循环求圆周率
- 使用javamail出现java.net.SocketException: Network is unreachable: connect异常 解决方法
- Myeclipse中修改JSP页面的pageEncoding默认编码
- 看看Spring的源码(一)——Bean加载过程
- java计算两个日期之间相隔的天数
- javassist 初步学习
- 浅析Java中的final关键字
- 论JAVA集合的实现细节,Map和List的联系