工厂模式-工厂方法模式
1.产品类
1.1产品的统一接口
/**
* @Desc:产品的接口
* @author zy
* @date 2016年6月21日下午4:40:33
*/
public interface Product {
/**
* @Desc:获取具体的产品
* @author:zy
* @version: 2016年6月21日 下午5:00:37
*/
public void getDetailProduct();
}
1.2 A产品和B产品
public class A implements Product{
@Override
public void getDetailProduct() {
System.out.println("get a product");
}
}
public class B implements Product{
@Override
public void getDetailProduct() {
System.out.println("get b product");
}
}
2.工厂方法
/**
* Description:简单工厂,负责生产简单、单一的产品
* @author zy
* @date 2016年6月1日下午3:02:40
*/
public class SimpleFactory {
/**
* @Desc:根据具体的参数,获取对应的实例
* @param type
* @return:
* @author:zy
* @version: 2016年6月21日 下午5:24:03
*/
public Product getFactory(Integer type){
if(1 == type){
return new A();
}else if(2 == type){
return new B();
}
return null;
}
}
3.测试
tips:
工厂方法模式,根据不同的传入条件,返回单一、简单的产品,传入条件的方式,可以使用if else,也可以使用switch case的判断
个人觉得,学习难度不高,使用频率一般般。
缺点:
使用角度:使用的时候,传入参数,可能没有对应的分支,或者传入的参数有误
编程原则:违反了开闭原则,假如我想在工厂方法里添加一个分支,得修改工厂方法的核心方法