자바 디자인 패턴 Factory의 활용

댜댜·2022년 12월 1일
0

Java

목록 보기
1/1

자바 디자인 패턴 : Factory


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입니다!)를 생성해서 팩토리를 통해 호출한 값을 반환 받습니다.

  1. Test class에서 Factory객체를 선언한다.
  2. Factory 객체를 통해서 메서드를 사용하고 입력받은 값을 Shape타입의 변수에 대입합니다.
  3. shape1에는 Circle 클래스의 객체가 선언 되었으니, shape1을 통해서 Circle 클래스의 메서드를 수행할 수 있습니다.
profile
개발자 시켜줭

0개의 댓글