티스토리 뷰

프로그램을 구현하면서 입력값 조건에 맞는 객체가 반환이 되도록 구현해야 하는 코드가 있었다.

아래 코드는 입력된 점의 개수에 따라 도형의 모양을 출력하는 코드이다. 점이 2개면 직선, 3개면 삼각형, 4개면 사각형을 반환하도록 되어있다.

현재는 조건문이 3개이지만, 만약 십이각형, 십삼각형 등의 다각형이 계속 추가된다고 한다면,  조건문은 계속 늘어날 것이다.

그렇다면 추후 유지보수가 굉장히 어려울 것이라고 생각된다. 그래서 이부분을 수정해보았다.

    public static Figure create(String[] inputPoint) throws PointException {
        if(inputPoint.length == 2) {
           return new Line(init(inputPoint));
        } else if(inputPoint.length == 3) {
           return new Triangle(init(inputPoint));
        } else if(inputPoint.length == 4) {
           return new Rectangle(init(inputPoint));
        } 
        throw new PointException("직선, 삼각형, 직사각형이 아닌 형태로 입력하셨습니다.");
    }


class.forName() 메소드를 이용한 동적객체 생성 방법으로 구현!

각 도형마다 꼭지점의 수가 다르기 때문에 꼭지점을 Key값으로 가지고 있는 Map 사용했다. 그리고 value  값으로 동적객체로 생성할 클래스의 이름을 보관하고 있다.

꼭지점의 갯수(즉, Map의 Key)를 전달받으면 생성할 객체의 클래스(즉, Map의 value)를 get()해서 바로 생성한다.

생성하는 과정에서 Class.forName()  과 getConstructor(), newInstance() 메소드를 사용한다.

 - Class.forName() : 매개변수로 전달된 이름의 클래스 또는 인터페이스의 클래스 객체를 생성

 - getConstructor() : 클래스 객체의 생성자 객체 생성 (단, public 접근제한자에 해당되는 생성자 객체만 생성 가능)

 - newInstance() :  객체 생성

마지막으로, 인터페이스의 다형성을 활용하여, 결과값을 리턴! 정리하지면, if-else 제거를 위해, 동적객체 생성 및 다형성을 활용

private static Map

constructorMap = new HashMap<>(); static { constructorMap.put(2, "domain.Line"); constructorMap.put(3, "domain.Triangle"); constructorMap.put(4, "domain.Rectangle"); } public static Figure create(String[] inputPoint) throws PointException { Constructor constructor = null; try { constructor = Class.forName(constructorMap.get(inputPoint.length)).getConstructor(List.class); return (Figure)constructor.newInstance(init(inputPoint)); } catch (Exception e) { } throw new PointException("직선, 삼각형, 직사각형이 아닌 형태로 입력하셨습니다."); }


공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함