设计模式--工厂设计模式(一)

工厂设计模式:就是当我们需要批量创建多种类型的对象时;需要用到,主要分为三种形式;
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();

}
}

结果一看就知道;
<script type="text/javascript" id="wumiiRelatedItems"> </script>
 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值