参考
什么是工厂模式?
工厂方法模式(又名工厂模式)是一种创建模式。创建模式通过隐藏对象的创建方式来抽象对象实例化过程,并使系统独立于对象创建过程。
抽象工厂模式是比工厂方法模式高一级的抽象,这意味着它返回工厂类。
抽象工厂模式示例
常量
public interface Const {
public static final int SHAPE_CIRCLE =1;
public static final int SHAPE_SQUARE =2;
public static final int SHAPE_HEXAGON =3;
}
形状工厂
public abstract class ShapeFactory {
public abstract Shape getShape(int shapeId);
}
除了SimpleShapeFactory
我们创建一个新的:
复杂形状工厂
public class ComplexShapeFactory extends ShapeFactory {
public Shape getShape(int shapeTypeId){
Shape shape = null;
if(shapeTypeId == Const.SHAPE_HEXAGON) {
shape = new Hexagon();//complex shape
}
else{
// drop an error
};
return shape;
}
}
现在让我们在抽象工厂创建,它返回以下类型之一ShapeFactory
:
形状工厂类型
public class ShapeFactoryType {
public static final int TYPE_SIMPLE = 1;
public static final int TYPE_COMPLEX = 2;
public ShapeFactory getShapeFactory(int type) {
ShapeFactory sf = null;
if(type == TYPE_SIMPLE) {
sf = new SimpleShapeFactory();
}
else if (type == TYPE_COMPLEX) {
sf = new ComplexShapeFactory();
}
else throw new BadShapeFactoryException("No factory!!");
return sf;
}
}
现在主要调用:
ShapeFactoryType abFac = new ShapeFactoryType();
ShapeFactory factory = null;
Shape s = null;
//returns a ShapeFactory but whether it is a
//SimpleShapeFactory or a ComplexShapeFactory is not known to the caller.
factory = abFac.getShapeFactory(1);//returns SimpleShapeFactory
//returns a Shape but whether it is a Circle or a Pentagon is
//not known to the caller.
s = factory.getShape(2); //returns square.
s.draw(); //draws a square
//returns a ShapeFactory but whether it is a
//SimpleShapeFactory or a ComplexShapeFactory is not
//known to the caller.
factory = abFac.getShapeFactory(2);
//returns a Shape but whether it is a Circle or a Pentagon is
//not known to the caller.
s = factory.getShape(3); //returns a pentagon.
s.draw(); //draws a pentagon
来自 DocumentBuilderFactory
DocumentBuilderFactory
就像ShapeFactoryType
在示例中一样。
返回 a基于的newInstance(String factoryClassName,ClassLoader classLoader)
新实例(在我的例子中,我使用了and )。DocumentBuilderFactory
factoryClassName
abFac.getShapeFactory(1);
abFac.getShapeFactory(2);