您的位置:首页 > 其它

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

2015-12-24 10:28 218 查看
工厂设计模式:就是当我们需要批量创建多种类型的对象时;需要用到,主要分为三种形式;

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();

}

}

结果一看就知道;



转发至微博
 



转发至微博
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: