简单工厂模式类图:
***************************************************************************************************
简单工厂模式目的:
提供一个类,由它负责根据一定的条件创建某一具体类的实例,客户端不参与创建具体产品,仅通过传入参数选择需要“消费”对象。而不必管这些对象究竟如何创建及如何组织的,从而使得客户端和实现之间的解耦
****************************************************************************************************
简单工厂模式的优势:
分离对象的创建和使用
****************************************************************************************************
简单工厂模式的缺点:
多一种产品,就要修改工厂类,违背了OCP原则。
****************************************************************************************************
简单工厂模式的使用场景:
工厂类负责创建的对象比较少;
客户只知道传入工厂类的参数,对于如何创建对象(逻辑)不关心;
由于简单工厂很容易违反高内聚责任分配原则,因此一般只在很简单的情况下应用。
****************************************************************************************************
简单工厂模式通用代码:
package com.imo.simpleFactory;
import com.imo.Main;
public class Client {
public static void main(String[] args) throws Exception {
Product product = Factory.createProduct(ProductA.class);
product.operation();
product = Factory.createProduct(ProductB.class);
product.operation();
product = Factory.createProduct(Main.class);
product.operation();
}
}
package com.imo.simpleFactory;
public class Factory {
public static Product createProduct(Class<?> product)
throws Exception {
if (product.equals(ProductA.class)) {
return new ProductA();
} else if (product.equals(ProductB.class)) {
return new ProductB();
} else {
throw new Exception("不能生产此类产品");
}
}
}
package com.imo.simpleFactory;
public interface Product {
public void operation();
}
package com.imo.simpleFactory;
public class ProductA implements Product {
@Override
public void operation() {
// TODO Auto-generated method stub
System.out.println("ProductA");
}
}
package com.imo.simpleFactory;
public class ProductB implements Product {
@Override
public void operation() {
// TODO Auto-generated method stub
System.out.println("ProductB");
}
}
****************************************************************************************************
补充:可以通过方法的重裁使工厂类更加优雅。
****************************************************************************************************
以上文字大部分是网上抄的,连图片都是抄的,只不过自己组织了一下。从前面的文字,简单工厂模式的优势是分离了对象的创建和使用,我就他妈的搞不懂了,我们不是已经很习惯创建对象,然后使用对象么?现在对象让人家帮我们创建,我们使用即可,这有什么本质上得好处?想来想去,觉得只可能是对象的创建比较复杂,不应该让使用者接触这些细节。有想法的朋友可以留言,一起讨论。