GOF - 템플릿 메소드 패턴

템플릿 메소드 패턴

  • 클래스의 구현중 자주 변할 수 있는 부분의 구조만을 제공하고 구체적인 구현의 책임은 서브 클래스로 미루는 패턴

활용성

  • 어떤 한 알고리즘을 이루는 부분 중 변하지 않는 부분을 한번 정의해 놓고 다양해질 수 있는 부분은 서브클래스에서 정의할 수 있도록 남겨두고자 할 때
  • 서브 클래스 사이에서 공통적인 행동을 추출하여 하나의 공통 클래스에 몰아둠으로써 코드 중복을 피하고 싶을때
  • 서브클래스의 확장을 제어할 수 있음

구조

  • AbstractClass : 서브클래스들의 재정의를 통해 구현해야 하는 알고리즘 처리 단계 내의 기본연산
  • ConcreteClass : 서브클래스마다 달라진 알고리즘 처리 단계를 수행하기 위한 기본 연산 구현

예제코드

public abstract class DBConnector {

	public abstract Connection getConnection();

	public void doAnyThing() {
		String sql = "select * from study";

		try (Statement stmt = getConnection().createStatement()) {
			ResultSet rs = stmt.executeQuery(sql);
			while (rs.next()) {
				String text = rs.getString("text");
				System.out.println("text : " + text);
			}
		} catch (SQLException throwables) {
			throwables.printStackTrace();
		}

	}

}

public class MariaDBConnector extends DBConnector{
	@Override
	public Connection getConnection() {

		Connection connection = null;
		try {
			Class.forName("org.mariadb.jdbc.Driver");

			String url = "jdbc:mariadb://localhost:3307/secret_study?characterEncoding=UTF-8&serverTimezone=UTC";
			connection = DriverManager.getConnection(url, "root", "study0718");

		} catch (ClassNotFoundException | SQLException e) {
			e.printStackTrace();
		}
		return connection;
	}
}

public class MysqlDBConnector extends DBConnector {
	@Override
	public Connection getConnection() {

		Connection connection = null;
		try {
			Class.forName("com.mysql.jdbc.Driver");

			String url = "jdbc:mysql://localhost:3306/study?characterEncoding=UTF-8&serverTimezone=UTC";
			connection = DriverManager.getConnection(url, "root", "study1234");

		} catch (ClassNotFoundException | SQLException e) {
			e.printStackTrace();
		}
		return connection;
	}

}
  • Main.java
public class Main {
	public static void main(String[] args) {
		DBConnector dbConnector = new MysqlDBConnector();

		System.out.println("===== my sql connector test start ===== ");
		dbConnector.doAnyThing();
		System.out.println("===== my sql connector test end =====");

		System.out.println();

		dbConnector = new MariaDBConnector();
		System.out.println("===== mariaDB connector test start ===== ");
		dbConnector.doAnyThing();
		System.out.println("===== mariaDB connector test end =====");
	}
}

결론

  • 공통적인 부분은 구현해놓고 변경될 부분만 서브클래스로 책임을 넘기는 경우 = 팩토리 메소드 패턴

  • 실제로 많은 패턴들의 구현 방법임 => 추상팩토리, 팩토리 메소드

  • 그러나 대다수의 경우 전략 패턴이 많은 대안으로 사용됨, (전략 패턴은 서브 클래싱을 하지 않기 때문에 확장에 자유로움)

  • 다만 공통적으로 사용해야할 메소드가 많을 경우에는 사용해볼법한 패턴

좋은 웹페이지 즐겨찾기