设计模式--工厂设计模式(一)
2015-12-24 10:28
218 查看
工厂设计模式:就是当我们需要批量创建多种类型的对象时;需要用到,主要分为三种形式;
1
静态工厂,也叫简单工厂模式,就是你传一个类型我创建对应的类型,Spring中主要用到的就是这种模式:
不多说,直接上代码:通用的产品接口,Product
,这个看需求,也可以定义为抽象类,根据你的对象之间的关系来定的
两个产品实现类
工厂:
是根据你的传递的字符串名称进行判断的,是不是很像Spring的做法;
测试:
结果一看就知道;
转发至微博
转发至微博
1
静态工厂,也叫简单工厂模式,就是你传一个类型我创建对应的类型,Spring中主要用到的就是这种模式:
不多说,直接上代码:通用的产品接口,Product
,这个看需求,也可以定义为抽象类,根据你的对象之间的关系来定的
package com.lrq.statics.factory; public interface Product { public void work(); }
两个产品实现类
package com.lrq.statics.factory; public class Bus implements Product { @Override public void work() { System.out.println("公共汽车在工作"); } } package com.lrq.statics.factory; public class Car implements Product{ @Override public void work() { System.out.println("car在工作"); } }
工厂:
package com.lrq.statics.factory; public class StaticFactory { public static Product create(String type) { if(type.equals("Bus")){ return new Bus(); }else if(type.equals("Car")){ return new Car(); }else{ throw new RuntimeException("要创建的产品不存在;"); } } }
是根据你的传递的字符串名称进行判断的,是不是很像Spring的做法;
测试:
public class StaticFactoryTest { @Test public void test(){ Product product = StaticFactory.create("Car"); product.work(); Product product2 = StaticFactory.create("Bus"); product2.work(); } }
结果一看就知道;
转发至微博
转发至微博
相关文章推荐
- 设计模式--单例设计模式
- 反射技术实现POI表格信息的注入
- Hibernate+SpringMVC整合:实战三,…
- Hibernate+SpringMVC整合:实战二,…
- Hibernate+SpringMVC整合实战一:搭…
- DAO层重构
- Action层重构
- service层重构的解决方案(三种解决…
- mybatis笔记
- Spring定时器的使用
- 数据结构课程设计——学生成绩管理系统
- struts总结完整整理版
- struts2总结:草稿
- Spring的总结
- struts2中默认拦截器栈中的拦截器…
- 动态代理模式--自定义数据源的终极…
- Git reset 回退项目某个节点版本
- kali postgress connection
- Ajax—初识
- 装饰设计模式---自定义数据源