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;是根据你的传递的字符串名称进行判断的,是不是很像Spring的做法;
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("要创建的产品不存在;");
}
}
}
测试:
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>