Ayden's journal

브릿지 패턴

브리지 패턴(Bridge Pattern)은 객체의 구조와 구현을 분리하여, 두 부분을 독립적으로 변경할 수 있도록 하는 디자인 패턴이다. 이 패턴은 추상화(Abstraction)와 구현(Implementation)을 분리함으로써, 각 부분을 독립적으로 변경하고 확장할 수 있게 한다. 즉, 추상화 계층과 구현 계층이 서로 독립적으로 발전할 수 있도록 도와주며, 서로의 변경이 다른 부분에 영향을 미치지 않도록 한다.

브리지 패턴은 주로 클래스나 객체가 두 가지 이상의 변형이 필요할 때 유용하다. 예를 들어, 다양한 형태의 DB 연결 객체와 다양한 Logger 객체가 있을 때, DB 연결 객체의 형태와 Logging 방식을 각각 독립적으로 변경할 수 있도록 하여 유연성을 제공한다. 이를 통해 코드 중복을 줄이고, 시스템의 확장성과 유지보수성을 높일 수 있다.

 

// Implementor - DB 연결 인터페이스
class DBConnection {
connect() {
throw new Error("This method should be overridden!");
}
}
// Concrete Implementor - MySQL 연결
class MySQLConnection extends DBConnection {
connect() {
console.log("Connecting to MySQL database...");
}
}
// Concrete Implementor - PostgreSQL 연결
class PostgreSQLConnection extends DBConnection {
connect() {
console.log("Connecting to PostgreSQL database...");
}
}
// Implementor - Logger 인터페이스
class Logger {
log(message) {
throw new Error("This method should be overridden!");
}
}
// Concrete Implementor - 콘솔 로그
class ConsoleLogger extends Logger {
log(message) {
console.log(`Console Logger: ${message}`);
}
}
// Concrete Implementor - 파일 로그
class FileLogger extends Logger {
log(message) {
console.log(`File Logger: ${message}`);
}
}
// Abstraction - DB 서비스
class DBService {
constructor(dbConnection, logger) {
this.dbConnection = dbConnection;
this.logger = logger;
}
execute() {
this.dbConnection.connect();
this.logger.log("DB operation executed.");
}
}
// 클라이언트 코드
const mySQLConnection = new MySQLConnection();
const postgreSQLConnection = new PostgreSQLConnection();
const consoleLogger = new ConsoleLogger();
const fileLogger = new FileLogger();
// MySQL 연결 + 콘솔 로깅
const mySQLService = new DBService(mySQLConnection, consoleLogger);
mySQLService.execute();
// 출력:
// Connecting to MySQL database...
// Console Logger: DB operation executed.
// PostgreSQL 연결 + 파일 로깅
const postgresService = new DBService(postgreSQLConnection, fileLogger);
postgresService.execute();
// 출력:
// Connecting to PostgreSQL database...
// File Logger: DB operation executed.

 

블로그의 프로필 사진

블로그의 정보

Ayden's journal

Beard Weard Ayden

활동하기