Factory desing pattern implemented in Java.
This pattern is used when there are many children of one class, and you want to take responsibility of creating new instances of classes from user.
Circle at 4.0, 5.0 Circle at 2.0, 7.0 Circle at -3.0, 12.0 base
Main.java
package factory; // ? 2019 TheFlyingKeyboard and released under MIT License // theflyingkeyboard.net public class Main { public static void main(String[] args) { Shape circle = ShapeFactory.create(4, 5, ShapeType.CIRCLE); Shape square = ShapeFactory.create(2, 7, ShapeType.SQUARE); Shape triangle = ShapeFactory.create(-3, 12, ShapeType.TRIANGLE); circle.showInfo(); square.showInfo(); triangle.showInfo(); } }
Shape.java
package factory; // ? 2019 TheFlyingKeyboard and released under MIT License // theflyingkeyboard.net public abstract class Shape { private double posX; private double posY; public Shape(double posX, double posY) { this.posX = posX; this.posY = posY; } public double getPosX() { return posX; } public double getPosY() { return posY; } public abstract void showInfo(); }
Circle.java
package factory; // ? 2019 TheFlyingKeyboard and released under MIT License // theflyingkeyboard.net public class Circle extends Shape { public Circle(double posX, double posY) { super(posX, posY); } @Override public void showInfo() { System.out.println("Circle at " + getPosX() + ", " + getPosY()); } }
Square.java
package factory; // ? 2019 TheFlyingKeyboard and released under MIT License // theflyingkeyboard.net public class Square extends Shape { public Square(double posX, double posY) { super(posX, posY); } @Override public void showInfo() { System.out.println("Circle at " + getPosX() + ", " + getPosY()); } }
Triangle.java
package factory; // ? 2019 TheFlyingKeyboard and released under MIT License // theflyingkeyboard.net public class Triangle extends Shape { public Triangle(double posX, double posY) { super(posX, posY); } @Override public void showInfo() { System.out.println("Circle at " + getPosX() + ", " + getPosY()); } }
ShapeType.java
package factory; // ? 2019 TheFlyingKeyboard and released under MIT License // theflyingkeyboard.net public enum ShapeType { CIRCLE, SQUARE, TRIANGLE }
ShapeFactory.java
package factory; // ? 2019 TheFlyingKeyboard and released under MIT License // theflyingkeyboard.net public class ShapeFactory { public static Shape create(double posX, double posY, ShapeType shapeType){ switch (shapeType) { case CIRCLE: return new Circle(posX, posY); case SQUARE: return new Square(posX, posY); case TRIANGLE: return new Triangle(posX, posY); } return null; } }
Java Factory