https://github.com/JiMandy00/java-basic-exercise/commit/0f8f84b502d5fb16d9cc7732117f6f49f3fc10d3
👾 객체 생성을 대신 수행해주는 공장, 인터페이스 구현체를 조립해준다.
public interface Shape {
void draw();
}
Shape 인터페이스를 만듭니다. 해당 인터페이스는 void draw();를 선언합니다.
public class Circle implements Shape{
@Override
public void draw() {
System.out.println("it's Circle");
}
}
public class Rectangle implements Shape{
@Override
public void draw() {
System.out.println("it's is rectangle");
}
}
public class Square implements Shape{
@Override
public void draw() {
System.out.println("It'square");
}
}
Shape 인터페이스를 구현하는 Circle, Rectangle, Square 클래스를 만들어줍니다.
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;
}
}
ShapeFactory에는 Interface를 구현한 Class를 모아서(?) 타 클래스에게 Circle, Rectangle, Suqre 클래스 객체를 반환해줍니다.
public class Test {
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();
}
}
Test(실제 Test 역할의 클래스가 아니라 이름만 Test입니다!)를 생성해서 팩토리를 통해 호출한 값을 반환 받습니다.