先通过例子理解一下
第1步:创建一个接口
Shape.java
1 public interface Shape { 2 void draw(); 3 }
第2步:创建几个实现类
Rectangle.java
1 public class Rectangle implements Shape { 2 3 @Override 4 public void draw() { 5 System.out.println("Inside Rectangle::draw() method."); 6 } 7 }
Square.java
1 public class Square implements Shape { 2 3 @Override 4 public void draw() { 5 System.out.println("Inside Square::draw() method."); 6 } 7 }
Circle.java
1 public class Circle implements Shape { 2 3 @Override 4 public void draw() { 5 System.out.println("Inside Circle::draw() method."); 6 } 7 }
第3步:创建工厂根据给定的信息生成具体类的对象
ShapeFactory.java
1 public class ShapeFactory { 2 3 //use getShape method to get object of type shape 4 public Shape getShape(String shapeType){ 5 if(shapeType == null){ 6 return null; 7 } 8 if(shapeType.equalsIgnoreCase("CIRCLE")){ 9 return new Circle(); 10 11 } else if(shapeType.equalsIgnoreCase("RECTANGLE")){ 12 return new Rectangle(); 13 14 } else if(shapeType.equalsIgnoreCase("SQUARE")){ 15 return new Square(); 16 } 17 18 return null; 19 } 20 }
第4步:演示使用工厂通过传递类型等信息来获取具体类的对象
FactoryPatternDemo.java
1 public class FactoryPatternDemo { 2 3 public static void main(String[] args) { 4 ShapeFactory shapeFactory = new ShapeFactory(); 5 6 //get an object of Circle and call its draw method. 7 Shape shape1 = shapeFactory.getShape("CIRCLE"); 8 9 //call draw method of Circle 10 shape1.draw(); 11 12 //get an object of Rectangle and call its draw method. 13 Shape shape2 = shapeFactory.getShape("RECTANGLE"); 14 15 //call draw method of Rectangle 16 shape2.draw(); 17 18 //get an object of Square and call its draw method. 19 Shape shape3 = shapeFactory.getShape("SQUARE"); 20 21 //call draw method of circle 22 shape3.draw(); 23 } 24 }
第5步:验证输出结果
验证输出结果如下:
1 Inside Circle::draw() method. 2 Inside Rectangle::draw() method. 3 Inside Square::draw() method.