Java 工厂模式基础:Shape 图形工厂入门
5 分钟搞懂工厂模式的最简形态
引言
工厂模式最简单的一种:把所有创建逻辑塞进一个工厂类。客户端只传类型字符串,工厂帮你造对象。
适合产品种类少且稳定的场景——产品一多就撑不住。
1. 核心结构
4 个角色:
- 抽象产品(
Shape):定义公共方法
- 具体产品(
Circle、Rectangle、Square):实现接口
- 工厂类(
ShapeFactory):根据参数决定造哪个
- 客户端:只调
factory.getShape("CIRCLE"),不知道是哪个类
2. 完整代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
| interface Shape { void draw(); }
class Circle implements Shape { @Override public void draw() { System.out.println("画一个圆形"); } }
class Rectangle implements Shape { @Override public void draw() { System.out.println("画一个矩形"); } }
class Square implements Shape { @Override public void draw() { System.out.println("画一个正方形"); } }
class ShapeFactory { public Shape getShape(String shapeType) { if (shapeType == null) return null; if (shapeType.equalsIgnoreCase("CIRCLE")) return new Circle(); if (shapeType.equalsIgnoreCase("RECTANGLE")) return new Rectangle(); if (shapeType.equalsIgnoreCase("SQUARE")) return new Square(); return null; } }
public class FactoryPatternDemo { public static void main(String[] args) { ShapeFactory factory = new ShapeFactory(); Shape shape1 = factory.getShape("CIRCLE"); shape1.draw(); Shape shape2 = factory.getShape("RECTANGLE"); shape2.draw(); Shape shape3 = factory.getShape("SQUARE"); shape3.draw(); } }
|
运行结果:
3. 一句话总结
工厂模式 = 把 new Xxx() 这类创建代码塞进工厂类,客户端只调 factory.getShape("类型") 拿到抽象产品。
下一步:看《Java 工厂模式详解:从简单工厂到工厂方法》,理解简单工厂为什么不够用、工厂方法怎么改进。