ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [DESIGN PATTERN] 템플릿 메서드 패턴
    study/design pattern 2020. 8. 30. 18:13

    템플릿 메서드 패턴 ( Template Method Pattern )

    알고리즘의 일부 또는 전부를 하위 클래스에서 구현하거나 위임하는데 사용한다.

    즉, 공통으로 사용하는 알고리즘은 부모 클래스에 정의하고 특정 부분에서 사용하는 알고리즘은 하위 클래스에서 수행하도록 설계하는 것이다.

    public abstract class HouseTemplate {
        public final void buildHouse(){
            buildFoundation();
            buildPillars();
            buildWalls();
            buildWindows();
            System.out.println("House is built");
        }
    
        private void buildWindows(){
            System.out.println("Building Glass Windows");
        }
    	
        private void buildFoundation(){
            System.out.println("Building foundation with cement, iron rods and sand");
        }
        
        public abstract void buildWalls();
        public abstract void buildPillars();
    }

    HouseTemplate라는 추상클래스를 정의하였다.

    HouseTemplate 클래스는 2개의 일반 메서드와 2개의 추상 메서드를 정의하고 있다.

    집을 만들 때 창문을 만들거나 기초 작업을 하는 것은 어떤 집인지에 상관없이 모두 같은 동작을 하기 때문에 일반 메서드로 정의하였고

    나무 집이냐, 유리집이냐에 따라서 벽과 기둥은 달라지게 되기 때문에 추상 메서드로 정의하였다.

    public class GlassHouse extends HouseTemplate {
        @Override
        public void buildWalls() {
            System.out.println("Building Glass Walls");
        }
    
        @Override
        public void buildPillars() {
            System.out.println("Building Pillars with glass coating");
        }
    }
    public class WoodenHouse extends HouseTemplate{
        @Override
        public void buildWalls() {
            System.out.println("Building Wooden Walls");
        }
    
        @Override
        public void buildPillars() {
            System.out.println("Building Pillars with Wood Coating");
        }
    }

     

    아래는 위 예제를 사용하는 메인 메서드이다.

    public static void main(String[] args) {
            HouseTemplate houseType = new WoodenHouse();
            houseType.buildHouse();
    
            System.out.println();
            System.out.println("===============");
            System.out.println();
    
            houseType = new GlassHouse();
            houseType.buildHouse();
    }
    
    
    //결과
    Building foundation with cement, iron rods and sand
    Building Pillars with Wood Coating
    Building Wooden Walls
    Building Glass Windows
    House is built
    
    ===============
    
    Building foundation with cement, iron rods and sand
    Building Pillars with glass coating
    Building Glass Walls
    Building Glass Windows
    House is built
    
    

     

     

    정리

    템플릿 메서드 패턴은 어떤 소스 코드 상의 알고리즘에서 특정 환경 및 상황에 맞게 확장 또는 변경해야할 경우 매우 유용한 패턴이다.

    추상클래스와 구현 클래스로 작성할 수 있고 공통적으로 사용되는 로직 부분은 추상 클래스의 일반 메서드로, 구현별로 달라질 수 있는 로직은 추상 메서드로 정의하여 구현 클래스에서 오버라이딩해서 사용할 수 있다.

    템플릿 메서드의 장점은 코드의 중복을 줄이고 하위 클래스의 역할을 줄일 수 있다는 점이다.

    공통된 로직은 상위 클래스에 모이기 때문에 핵심 로직에 대한 관리가 용이하고 객체를 추가하거나 확장하는 것이 용이해진다.

    반대로 추상 메서드가 많아지면 클래스 관리가 복잡하다는 단점이 있다. 추상 클래스와 구현 클래스간의 복잡성이 높아질 가능성도 있다.

    'study > design pattern' 카테고리의 다른 글

    [DESIGN PATTERN] Strategy 패턴  (0) 2020.08.30
    [DESIGN PATTERN] 빌더 패턴  (0) 2020.08.30
Designed by Tistory.