简单工厂模式又称静态工厂方法模式,简单工厂不是一个标准的设计模式(不属于GoF23种设计模式),但是它很常用。
定义:
提供一个创建对象实例的功能,而无须关心其具体实现。
简单工厂模式UML类图:
代码如下:
public class Client {
public static void main(String[] args) {
IFactory fac = new Factory();
IProduct pro = fac.createProduct("B");
pro.productMethod();
}
}
interface IFactory {
IProduct createProduct(String type);
}
class Factory implements IFactory {
@Override
public IProduct createProduct(String type) {
if (type.equals("A"))
return new ProductA();
if (type.equals("B"))
return new ProductB();
return null;
}
}
interface IProduct {
void productMethod();
}
class ProductA implements IProduct {
@Override
public void productMethod() {
System.out.println("ProductA");
}
}
class ProductB implements IProduct {
@Override
public void productMethod() {
System.out.println("ProductB");
}
}