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;
}
}
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 =====");
}
}
공통적인 부분은 구현해놓고 변경될 부분만 서브클래스로 책임을 넘기는 경우 = 팩토리 메소드 패턴
실제로 많은 패턴들의 구현 방법임 => 추상팩토리, 팩토리 메소드
그러나 대다수의 경우 전략 패턴이 많은 대안으로 사용됨, (전략 패턴은 서브 클래싱을 하지 않기 때문에 확장에 자유로움)
다만 공통적으로 사용해야할 메소드가 많을 경우에는 사용해볼법한 패턴