接口:
public interface Shape {
void draw();
}
实体类:
public class Rectangle implements Shape {
@Override
public void draw() {
System.out.println("Inside Rectangle:draw() method.");
}
}
public class Square implements Shape {
@Override
public void draw() {
System.out.println("Inside Square:draw() method.");
}
}
public class Circle implements Shape {
@Override
public void draw() {
System.out.println("Inside Circle:draw() method.");
}
}
创建一个工厂,生成基于给定信息的实体类的对象。
ShapeFactory.java
public class ShapeFactory {
public Shape getShape(String shapeType){
switch (shapeType) {
case "CIRCLE":
return new Circle();
case "RECTANGLE":
return new Rectangle();
case "SQUARE":
return new Square();
}
return null;
}
}
使用该工厂,通过传递类型信息来获取实体类的对象。
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();
//获取 Square 的对象,并调用它的 draw 方法
Shape shape3 = shapeFactory.getShape("SQUARE");
//调用 Square 的 draw 方法
shape3.draw();
}
}
验证输出。
Inside Circle:draw() method.
Inside Rectangle:draw() method.
Inside Square:draw() method.
本文介绍了一个简单的工厂模式实现案例,展示了如何使用工厂模式来创建不同类型的形状对象,包括圆形、矩形和正方形,并通过示例代码说明了其实现方式。

1114

被折叠的 条评论
为什么被折叠?



