Open Paransaik opened 9 months ago
디자인 패턴이란 기존 환경 내에서 반복적으로 일어나는 문제들을 어떻게 풀어나갈 것인가에 대한 일종의 솔루션 같은 것이다. 디자인 패턴 계의 교과서로 불리는 [GoF의 디자인패턴]에서는 객체지향적 디자인 패턴의 카테고리를 "생성 패턴(Creational Pattern)", "구조 패턴(Structural Pattern)", "행동 패턴(Behavioral Pattern)" 3가지로 구분하고 있다. | 생성 패턴(Creational Pattern) | 구조 패턴(Structural Pattern) | 행동 패턴(Behavioral Pattern) |
---|---|---|---|
Singleton | Adapter | Command | |
Abstract Factory | Composite | Interpreter | |
Factory Method | Decorator | Iterator | |
Builder | Facade | Mediator | |
Prototype | Flyweight | Memento | |
Proxy | Observer | ||
State | |||
Strategy | |||
Template Method |
어떤 클래스가 오직 하나의 객체만을 갖도록 하며, 프로그램 전반에 걸쳐 그객체 하나만 사용되도록 보장해야함.
public class Restaurant{
private static Restaurant _instance=null;
protected Restaurant() { . . . }
public static Restaurant getInstance() {
if(_instance==null){
_instance = new Restaurant();
}
return _instance;
}
}
2) 팩터리메서드(factory method) 어떤 클래스의 객체를 생성하기 위한 인터페이스를 제공하되, 하위 클래스에서 어떤 클래스를 생성할지 결정할 수 있도록 도와줌.
public class CardGame {
public static CardGame createCardGame (GameType type) {
if(type == GameType.Poker) {
return new PokerGame();
} else if ( type == GameType.BlackJack) {
return new BlackJackGame();
}
return null;
}
}
3) 추상팩토리패턴(Abstract Factory) 객체를 생성할 때 객체를 구성하는 부분을 추상화하여 여러 서브클래스가 상속을 통해 구현하여 구성하는 부분을 동일하게 유지하는 방법.
4) 빌더 패턴(Builder) 복잡한 객체의 생성을 표현으로 부터 분리시키는 것
Singleton pattern은 어플리케이션당 오직 하나의 인스턴스만 존재하도록 보장해주는 패턴입니다. 공유 자원을 관리하거나 cross-cutting services(e.g. logging)를 제공할 때 유용합니다.
코드 예제
@RestController
public class LibraryController {
@Autowired
private BookRepository repository;
@GetMapping("/count")
public Long findCount() {
System.out.println(repository);
return repository.count();
}
}
Factory Method pattern은 원하는 객체를 생성하기 위한 추상 메서드가 있는 팩토리 클래스를 생성한다. 종종 우리는 특정 컨텍스트를 기반으로 다른 객체를 생성한다. 2-1) Application Context Spring Framework는 이 기술을 Dependency Injection(DI)에서 사용한다. 기본적으로, Spring Framework는 Bean Container를 Bean을 생성하는 Factory로 취급한다. 따라서, Spring Framework는 BeanFactory Interface를 Bean Container의 추상화로 정의한다.
public interface BeanFactory {
getBean(Class<T> requiredType);
getBean(Class<T> requiredType, Object... args);
getBean(String name);
// ...
}
2-2) External Configuration Factory Method pattern은 Application의 동작을 외부 설정에 맞게 변경할 수 있기 때문에 다양하게 사용 가능합니다.
Proxy pattern은 한 객체(proxy)가 다른 객체(subject or service)로의 접근을 제어하도록 하는 기술이다. 일반적으로, Spring에서는 두 가지 타입의 Proxy를 사용합니다
@Service
public class BookManager {
@Autowired
private BookRepository repository;
@Transactional
public Book create(String author) {
System.out.println(repository.getClass().getName());
return repository.create(author);
}
}
3-2. CGLib Proxies
CGLib Proxies는 Spring Framework가 BookRepository를 감싸고 Bean들에게 create(...) 메서드를 원자적으로 실행하도록
지시하는 Proxy를 생성한다.
![image](https://github.com/ParansaikStudy/LDK-SpringBase/assets/91397068/2be8bccf-5b6f-4af5-a739-37c29dce5147)
4. Template pattern
다수의 프레임워크에는 상당량의 코드가 boilerplate code입니다.
예를 들어, DB에서 쿼리를 실행하기 위해선 다음 단계들이 필수적입니다.
1. Connection 생성
2. 쿼리 실행
3. cleanup 실행
4. Connection 종료
4-1) Templates & Callbacks
- 코드 예제
public abstract DatabaseQuery { public void execute() { Connection connection = createConnection(); executeQuery(connection); closeConnection(connection); } protected Connection createConnection() { // Connect to database... } protected void closeConnection(Connection connection) { // Close connection... } protected abstract void executeQuery(Connection connection); }
![image](https://github.com/ParansaikStudy/LDK-SpringBase/assets/91397068/d8d469be-0473-4c96-96e5-0e63f6a26644)
4-2) JdbcTemplate
- JdbcTemplate class는 query(String, ResultSetExtractor) 메서드를 제공한다.
- 코드 예제
public class JdbcTemplate {
public
- ResultSetExtractor는 ResultSet객체를 T타입의 도메인 객체로 변환해준다.
- 코드 예제
@FunctionalInterface
public interface ResultSetExtractor
- Spring framework는 보다 구체적인 Callback interface를 생성해 boilerplate code를 더욱 줄인다.
예를 들어, RowMapper interface는 단일행의 SQL 데이터를 T 타입의 도메인객체로 변환하는데 사용된다.
- 코드 예제
@FunctionalInterface
public interface RowMapper
- RowMapper interface를 예상되는 ResultSetExtractor에 적용하기 위해 Spring framework는
RowMapperResultSetExtractor class를 생성한다.
- 코드 예제
public class JdbcTemplate {
public
- row들을 반복하며 전체 ResultSet 객체를 전환하는 로직을 제공하는 대신, 단일행을 변환하는 방법에 대한 로직을
제공할 수 있다.
- 코드 예제
public class BookRowMapper implements RowMapper
※ 참고자료: https://loginfo.tistory.com/2
개요