DesignPattern
资源简介
设计模式是解决软件设计中常见问题的可重用解决方案。例如,工厂模式可以在不暴露对象创建逻辑的情况下创建对象。在Java中,可以使用以下代码实现: interface Shape { void draw(); } class Circle implements Shape { @Override public void draw() { System.out.println("Inside Circle::draw() method."); } } class Rectangle implements Shape { @Override public void draw() { System.out.println("Inside Rectangle::draw() method."); } } class ShapeFactory { 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(); } return null; } } public class FactoryPatternDemo { public static void main(String[] args) { ShapeFactory shapeFactory = new ShapeFactory(); Shape shape1 = shapeFactory.getShape("CIRCLE"); shape1.draw(); Shape shape2 = shapeFactory.getShape("RECTANGLE"); shape2.draw(); } } 这段代码展示了工厂模式在Java中的应用,通过ShapeFactory来获取不同类型的Shape对象,而无需了解其创建细节。
- 资源类型
- 软件
- 第三方域名
- github.com
- 索引时间
- 2026-08-04 01:35
访问第三方资源链接需要 VIP 权限。注册与搜索永久免费,VIP 仅用于访问第三方链接。