import com.cy.shape.Circle;
import com.cy.shape.Rectangle;
import com.cy.shape.Shape;
import com.cy.shape.Square;
public class ShapeFactory {
public Shape getShape(String shape) {
if (shape == null) {
return null;
}
if (shape.equalsIgnoreCase("CIRCLE")) {
return new Circle();
} else if (shape.equalsIgnoreCase("RECTANGLE")) {
return new Rectangle();
} else if (shape.equalsIgnoreCase("SQUARE")) {
return new Square();
}
return null;
}
}
public class Square implements Shape {
@Override
public void draw() {
System.out.println("Inside Square::draw() method.");
}
}
public interface Shape {
void draw();
}
public class Rectangle implements Shape {
@Override
public void draw() {
System.out.println("Inside Rectangle::draw() method.");
}
}
public class Circle implements Shape {
@Override
public void draw() {
System.out.println("Inside Circle::draw() method.");
}
}
package com.cy.test;
import com.cy.factory.ShapeFactory;
import com.cy.shape.Shape;
public class FactoryPatternDemo {
public static void main(String[] args) {
ShapeFactory shapeFactory = new ShapeFactory();
Shape shape1 = shapeFactory.getShape("RECTANGLE");
shape1.draw();
Shape shape2 = shapeFactory.getShape("SQUARE");
shape2.draw();
Shape shape3 = shapeFactory.getShape("CIRCLE");
shape3.draw();
}
}