工厂模式是Java中最常用的设计模式之一,这种设计模式属于创建模式,因为该模式提供了创建对象的最佳方法之一。
无涯教程将创建一个 Shape 接口和实现 Shape 接口的具体类。下一步将定义工厂类 ShapeFactory 。
FactoryPatternDemo ,演示类将使用 ShapeFactory 获得 Shape 对象。它将( Circle/Rectangle/Square )传递给 ShapeFactory 以获取所需的对象类型。
第1步 - 创建一个接口。
Shape.java
public interface Shape { void draw(); }
第2步 - 创建实现相同接口的具体类。
Rectangle.java
public class Rectangle implements Shape { @Override public void draw() { System.out.println("Inside Rectangle::draw() method."); } }
Square.java
public class Square implements Shape { @Override public void draw() { System.out.println("Inside Square::draw() method."); } }
Circle.java
public class Circle implements Shape { @Override public void draw() { System.out.println("Inside Circle::draw() method."); } }
第3步 - 创建一个Factory以根据给定的信息生成具体类的对象。
ShapeFactory.java
public class ShapeFactory { //use getShape method to get object of type shape public Shape getShape(String shapeType){ if(shapeType == null){ return null; } if(shapeType.equalsIgnoreCase("CIRCLE")){ return new Circle(); } else if(shapeType.equalsIgnoreCase("RECTANGLE")){ return new Rectangle(); } else if(shapeType.equalsIgnoreCase("SQUARE")){ return new Square(); } return null; } }
第4步 - 使用工厂通过传递诸如类型信息来获取具体类的对象。
FactoryPatternDemo.java
public class FactoryPatternDemo { public static void main(String[] args) { ShapeFactory shapeFactory=new ShapeFactory(); //获取一个 Circle 对象并调用它的 draw 方法。 Shape shape1=shapeFactory.getShape("CIRCLE"); //调用Circle的draw方法 shape1.draw(); // 获取一个 Rectangle 对象并调用它的 draw 方法。 Shape shape2=shapeFactory.getShape("RECTANGLE"); // 调用 Rectangle 的 draw 方法 shape2.draw(); //get an object of Square and call its draw method. Shape shape3=shapeFactory.getShape("SQUARE"); // 调用正方形的draw方法 shape3.draw(); } }
第5步 - 验证输出。
Inside Circle::draw() method. Inside Rectangle::draw() method. Inside Square::draw() method.
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)