图片和代码来自原文,原文链接:
http://www.tutorialspoint.com/design_pattern/factory_pattern.htm
-----------------------------------------------------------------------------------------------
工厂模式是Java中使用最多的设计模式之一,属于创建型模式,提供了创建对象的最佳实践方法之一。
通过工厂模式,用户不使用显式的对象创建方法,而是通过一个公共的接口来创建对象。
实现
我们将创建一个接口Shape,一些实现了Shape接口的类,一个工厂类ShapeFactory用来创建具体的对象。
FactoryPatternDemo使用ShapeFactory获取对象,它传递相应的类型信息(CIRCLE / RECTANGLE / SQUARE)给ShapeFactory来获取需要的对象。
步骤1:新建一个接口Shape
Shape.java
publicinterfaceShape{
void draw();
}
步骤2:创建实现Shape接口的类
Rectangle.java
publicclassRectangleimplementsShape{
@Override
publicvoid draw(){
System.out.println("Inside Rectangle::draw() method.");
}
}
Square.java
publicclassSquareimplementsShape{
@Override
publicvoid draw(){
System.out.println("Inside Square::draw() method.");
}
}
Circle.java
publicclassCircleimplementsShape{
@Override
publicvoid draw(){
System.out.println("Inside Circle::draw() method.");
}
}
步骤3:创建一个工厂,根据传入的信息生成具体类型的对象
ShapeFactory.java
publicclassShapeFactory{
//use getShape method to get object of type shape
publicShape getShape(String shapeType){
if(shapeType ==null){
returnnull;
}
if(shapeType.equalsIgnoreCase("CIRCLE")){
returnnewCircle();
}elseif(shapeType.equalsIgnoreCase("RECTANGLE")){
returnnewRectangle();
}elseif(shapeType.equalsIgnoreCase("SQUARE")){
returnnewSquare();
}
returnnull;
}
}
步骤4:FactoryPatternDemo通过向工厂类传递类型信息,获取具体的对象
FactoryPatternDemo.java
publicclassFactoryPatternDemo{
publicstaticvoid main(String[] args){
ShapeFactory shapeFactory =newShapeFactory();
//get an object of Circle and call its draw method.
Shape shape1 = shapeFactory.getShape("CIRCLE");
//call draw method of Circle
shape1.draw();
//get an object of Rectangle and call its draw method.
Shape shape2 = shapeFactory.getShape("RECTANGLE");
//call draw method of Rectangle
shape2.draw();
//get an object of Square and call its draw method.
Shape shape3 = shapeFactory.getShape("SQUARE");
//call draw method of circle
shape3.draw();
}
}
步骤5:输出
Inside Circle::draw() method.
Inside Rectangle::draw() method.
Inside Square::draw() method.