> For the complete documentation index, see [llms.txt](https://heronyang.gitbook.io/clean-up-your-spaghetti/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://heronyang.gitbook.io/clean-up-your-spaghetti/4_stand_on_giants/factory_pattern.md).

# Factory Pattern

## Problem

Who should be responsible for creating objects when there are special considerations, such as complex creation logic, a desire to separate the creation responsibilities for better cohesion, and so forth?

## Solution

Create a Pure Fabrication object called a Factory that handles the creation.

**Shape.java**

```java
public interface Shape {
    void draw();
}
```

**Rectangle.java**

```java
public class Rectangle implements Shape {
   @Override
   public void draw() {
      System.out.println("rectangle draw");
   }
}
```

**Square.java**

```java
public class Square implements Shape {
   @Override
   public void draw() {
      System.out.println("square draw");
   }
}
```

**Circle.java**

```java
public class Circle implements Shape {
   @Override
   public void draw() {
      System.out.println("circle draw");
   }
}
```

**ShapeFactory.java**

```java
public 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();
      } else if(shapeType.equalsIgnoreCase("SQUARE")) {
         return new Square();
      }

      return null;

   }

}
```

**FactoryPatternDemo.java**

```java
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();

      Shape shape3 = shapeFactory.getShape("SQUARE");
      shape3.draw();

   }
}
```

*Original example is from* [*tutorialspoint*](http://www.tutorialspoint.com/design_pattern/factory_pattern.htm)

## Think

* Think cohesion and coupling
* Think future reuse and modification
