1
\$\begingroup\$

Trying to learn the factory design pattern, came up with some code based on a Shape Factory (found this example here). Is this the right way to implement the factory pattern?

interface Shape{
 void draw();
}
class Rectangle implements Shape{
 @Override
 public void draw() {
 System.out.println(" Drawing A Rectangle!");
 }
}
class Circle implements Shape{
 @Override
 public void draw() {
 System.out.println(" Drawing A cIRCLE!");
 }
}
class Triangle implements Shape{
 @Override
 public void draw() {
 System.out.println(" Drawing A Triangle!");
 }
}
class ShapeFactory{
 public static Shape getShape(String shapeType)
 {
 Shape shape = null;
 switch(shapeType.toUpperCase()){
 case "CIRCLE":
 shape = new Circle();
 break;
 case "RECTANGLE":
 shape = new Rectangle();
 break;
 case "TRIANGLE":
 shape = new Triangle();
 break;
 }
 return shape;
 }
}
public class FactoryExample {
 public static void main(String[] args) {
 Shape s = ShapeFactory.getShape("rectangle");
 s.draw();
 s = ShapeFactory.getShape("triangle");
 s.draw();
 }
}
200_success
145k22 gold badges190 silver badges478 bronze badges
asked Mar 6, 2016 at 5:19
\$\endgroup\$
1
  • 1
    \$\begingroup\$ Try using constants to be passed to the factory for creation. This prevents typos from being introduced, e.g. ShapeFactory.createShape(Shape.TRIANGLE); \$\endgroup\$ Commented Mar 6, 2016 at 10:38

2 Answers 2

5
\$\begingroup\$

You could rewrite getShape as follows:

public static Shape getShape(String shapeType) {
 switch (shapeType.trim().toUpperCase()) {
 case "CIRCLE":
 return new Circle();
 case "RECTANGLE":
 return new Rectangle();
 case "TRIANGLE":
 return new Triangle();
 default:
 return null;
 }
}
answered Mar 6, 2016 at 8:22
\$\endgroup\$
2
\$\begingroup\$

Naming the method getShape(...) suggests that it's going to retrieve the same cached instance with every call. A more appropriate name to convey what the method does would be makeShape(...), or maybe newShape(...). (Unfortunately, you followed a bad example.)

answered Mar 6, 2016 at 9:57
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.