# design-pattern **Repository Path**: cckevincyh/design-pattern ## Basic Information - **Project Name**: design-pattern - **Description**: No description available - **Primary Language**: Java - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2020-09-24 - **Last Updated**: 2020-12-19 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # 设计模式 ## 工厂模式(factory pattern) > 工厂模式(Factory Pattern)是 Java 中最常用的设计模式之一。这种类型的设计模式属于创建型模式,它提供了一种创建对象的最佳方式。 > > 在工厂模式中,我们在创建对象时不会对客户端暴露创建逻辑,并且是通过使用一个共同的接口来指向新创建的对象。 ### 简单工厂模式 > 简单工厂(Simple Factory)模式,又称静态工厂方法模式(Static Factory Method Pattern)。 定义接口 ```java public interface Shape { void draw(); } ``` 创建实现类 ```java /** * 圆形 */ public class Circle implements Shape { public void draw() { System.out.println("Circle"); } } ``` ```java /** * 长方形 */ public class Rectangle implements Shape { public void draw() { System.out.println("Rectangle"); } } ``` ```java /** * 正方形 */ public class Square implements Shape { public void draw() { System.out.println("Square"); } } ``` 工厂类 ```java public class ShapeFactory { public static 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; } } ``` 测试方法 ```java public class ShapeMain { public static void main(String[] args) { Shape circle = ShapeFactory.getShape("CIRCLE"); Shape rectangle = ShapeFactory.getShape("RECTANGLE"); Shape square = ShapeFactory.getShape("SQUARE"); circle.draw(); rectangle.draw(); square.draw(); } } ``` 但是有个问题就是如果我们需要增加新的形状的时候,就需要修改`ShapeFactory`的`getShape`方法,这很明显违背了开闭原则(对于扩展是开放的,但是对于修改是封闭的)