Skip to content

Instantly share code, notes, and snippets.

@mattnicee7
Created December 20, 2021 22:20
Show Gist options
  • Save mattnicee7/3ef68f3e3e0da7d5359b5dd7c4d892d2 to your computer and use it in GitHub Desktop.
Save mattnicee7/3ef68f3e3e0da7d5359b5dd7c4d892d2 to your computer and use it in GitHub Desktop.
FactoryPattern
public class Application {
public static void main(String[] args) {
ShapeFactory shapeFactory = new ShapeFactory();
Shape shape1 = shapeFactory.getShape("CIRCLE");
shape1.draw();
// Output: Wow! you drawed a circle.
Shape shape2 = shapeFactory.getShape("RECTANGLE");
shape2.draw();
// Output: Wow. you drawed a rectangle.
Shape shape3 = shapeFactory.getShape("SQUARE");
shape3.draw();
// Output: Wow. you drawed a square.
}
}
public class Circle implements Shape {
@Override
public void draw() {
System.out.println("Wow! you drawed a circle.");
}
}
public class Rectangle implements Shape {
@Override
public void draw() {
System.out.println("Wow. you drawed a rectangle.");
}
}
public interface Shape {
void draw();
}
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;
}
}
public class Square implements Shape {
@Override
public void draw() {
System.out.println("Wow. you drawed a square.");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment