接码短信平台银盾智云简报
创建产品对象的接口。 具体工厂(ConcreteFactory):实现抽象工厂并创建特定类型产品的对象。 产品(Product):产品接口,定义产品对象的行为。 具体产品(ConcreteProduct):实现产品接口的具体产品对象。 注册表(Registry):包含所有已注册产品对象的中央注册表。 机制 其他对象可以通过注册表访问已注册的产品对象,使用其唯一标识符。 当产品对象不再需要时,它可以从注册表中注销。 优点 松散耦合:对象可以轻松访问和使用其他对象,而无需了解其具体实现。 易于查找和管理对象:注册表提供了一个中心位置来查找和管理对象。 示例代码 ```j多媒体a // 抽象工厂 interface ShapeFactory { Shape createShape(String shapeType); } // 具体工厂 class CircleFactory implements ShapeFactory { @Override public Shape createShape(String shapeType) { return new Circle(); } } // 产品 interface Shape { void draw(); } // 具体产品 class Circle implements Shape { @Override public void draw() { System.out.println("Drawing a circle"); } } // 注册表 class ShapeRegistry { private Map shapes = new HashMap<>(); public void registerShape(String shapeType, Shape shape) { shapes.put(shapeType, shape); } public Shape getShape(String shapeType) { return shapes.get(shapeType); } } // 主类 public class Main { public static void main(String[] args) { ShapeFactory shapeFactory = new CircleFactory(); Shape circle = shapeFactory.createShape("Circle"); ShapeRegistry registry = ShapeRegistry.getInstance(); registry.registerShape("Circle", circle); // 从注册表中获取对象 Shape retrievedCircle = registry.getShape("Circle"); retrievedCircle.draw(); } } ```