※ Design Pattern이란?
[Buschmann, et al. 1996]_ 최고의 캡슐화의 한 방법으로 매우 효율적으로 프로그래머들이 문제를 해결할 수 있을 것이다.
안정성, 확장성 등에도 효율적이며 패턴이 반복되는 설계문제를 해결하도록 하며 대표적으로 다음과 같은 예시들이 있다.

이렇게 많은 디자인 패턴 종류에서 유명한 3가지인 싱글톤, 팩토리 메소드, 브릿지 패턴을 이번에 정리할 것이다.
※ Singleton
하나의 (전역)인스턴스만 생성하여 사용하는 디자인 패턴.
인스턴스가 필요할 때, 기존의 인스턴스를 활용하는 것.
한번의 new를 통한 객체생성으로 메모리 낭비를 방지가능!
딱 하나의 독자적인 클래스생성을 진행하며 그 클래스의 객체가 복사되면 안된다.
[구조]

class Singleton {
private:
// 생성자는 private으로 막는다.
// 따라서 외부에서 new를 이용한 객체생성이 불가능하다.
Singleton();
Singleton(const Singleton& ref) { }
Singleton& operator=(const Singleton& ref) { }
~Singleton() { }
// 객체 하나를 담을 수 있는 포인터 변수를 선언
// 이때, static으로 선언해서 단 하나만 존재할 수 있게 한다.
static Singleton *single;
public:
// single을 가져오거나 해제하는 멤버함수 선언
// static변수에 접근하고 외부에서 쓸 수 있어야 해서 publc으로 지정
static Singleton *getInstance();
static void DestroySingle();
};
Singleton *Singleton::single = nullptr; // static멤버변수이기에 클래스 외부에서 초기화
Singleton::Singleton() { }
Singleton *Singleton::getInstance() {
if (!single) // single이 nullptr일 때,
single = new Singleton; // 새로 생성해 객체를 초기화
return single; // 앞으로 호출될 때마다 이미 생성된 객체를 return
}
void Singleton::DestroySingle() { // getInstance() 함수와 유사
if (!single)
return;
delete single;
single = nullptr;
}
※ Factory Method
객체생성이 복잡하거나 어렵다면, 이를 대행하는 함수를 두는 설계방식.객체를 생성하지만 생성자를 호출하지 않고 대행함수를 통해 간접적으로 객체를 생성한다.
팩토리 메서드 패턴은 복잡도가 낮고 높은 수준의 유연성을 제공해야할 때, 매우 유용하다.
즉, 생성자 기능을 대신하는 메소드를 별도로 정의하는 방식이다.
[구조 예시]

#include <iostream>
#include <string>
using namespace std;
class Product { // 인터페이스(interface) 선언
public:
virtual string Operation() const = 0;
virtual ~Product() { }
};
class ConcreteProduct1 : public Product { // 인터페이스 상속
public:
string Operation() const override {
return "{Result of the ConcreteProduct1}";
}
};
class ConcreteProduct2 : public Product { // 인터페이스 상속
public:
string Operation() const override {
return "{Result of the ConcreteProduct2}";
}
};
/* Product 인터페이스의 객체를 return하는 factory method를 선언하는 Creator 클래스
* Creator클래스의 하위 클래스는 factory method를 상속받음 */
class Creator { // 인터페이스 클래스는 선언만 진행 (구현X)
public:
virtual Product *FactoryMethod() const = 0;
virtual ~Creator(){};
/* factory method에서 반환된 product 객체에 의존한다. */
string SomeOperation() const {
// Product객체생성을 위한 factory method 호출.
Product *product = this->FactoryMethod();
string result = "Creator: 동일한 creator의 코드가 " + product->Operation() + "과 작동중";
delete product;
return result;
}
};
/* product type변환을 위해 factory method를 재정의하는 Concrete Creator 클래스들 */
class ConcreteCreator1 : public Creator {
public:
Product *FactoryMethod() const override {
return new ConcreteProduct1();
}
};
class ConcreteCreator2 : public Creator {
public:
Product *FactoryMethod() const override {
return new ConcreteProduct2();
}
};
/* ClientCode 함수는 ConcreteCreator 객체와 함께 작동
* 기본 인터페이스로 어떤 creator 하위클래스에도 전달 가능 */
void ClientCode(const Creator& creator) {
cout << "Client: I'm not aware of the creator's class, but it still works.\n" << creator.SomeOperation() << endl;
}
int main() {
cout << "App: Launched with the ConcreteCreator1.\n";
Creator *creator = new ConcreteCreator1();
ClientCode(*creator);
cout << endl;
cout << "App: Launched with the ConcreteCreator2.\n";
Creator *creator2 = new ConcreteCreator2();
ClientCode(*creator2);
delete creator;
delete creator2;
return 0;
}
※ Bridge pattern
구현부에서 추상층을 분리, 각각 독립적으로 변형과 확장이 가능하게 하는 패턴 java에선 super키워드도 사용
따라서 두 계층 모두 추상화된 상위 타입을 갖고 의존성은 상위 타입간에만 이뤄진다.
인터페이스와 구현방식이 완전 결합되는 것을 피할 때 사용
하위 클래스 구조가 서로 다른 형태이길 원할 때 사용
과거 C++개발자들은 컴파일 단축을 위해 Pimpl이라는 독특한 관례를 사용했다. (Pointer to Implement)
Pimpl은 말그대로 구현부를 포인터로 참조하는 것이다.
장점 1: 클래스의 private, protected멤버가 헤더로 노출되기에 불필요한 노출을 막을 수 있다.
장점 2: 숨겨진 구현클래스에 대한 수정이 바이너리 호환성에 영향X
장점 3: 헤더파일에 구현에 필요한 다른 헤더를 포함하지 않아도 된다.
컴포넌트 간 다양한 조합이 가능할 때 효과적이며 실제 구현을 모두 인터페이스에 위임한다.
[구조 예시]


Abstraction: 기능 계층의 최상위 클래스.
구현부분에 해당하는 클래스를 객체를 이용해 구현부분의 함수를 호출
Refind Abstraction: 기능 계층에서 새로운 부분을 확장한 클래스
Implementation: 추상클래스의 기능을 구현하기 위한 인터페이스 정의
Concrete Implementor: 실제 기능을 구현하는 것
#include <iostream>
#include <string>
using namespace std;
/******************************<인터페이스 구현>******************************/
class Implementation {
public:
virtual string OperationImplementation() const = 0; // 순수가상함수
virtual ~Implementation() { }
};
class ConcreteImplementationA : public Implementation {
public:
string OperationImplementation() const override {
return "ConcreteImplementationA: Here's the result on the platform A.\n";
}
};
class ConcreteImplementationB : public Implementation {
public:
string OperationImplementation() const override {
return "ConcreteImplementationB: Here's the result on the platform B.\n";
}
};
/******************************<추상클래스 구현>******************************/
class Abstraction {
protected:
// 인터페이스 클래스에 대한 포인터참조로 브릿지 패턴을 잘 나타내고 있음을 알 수 있다.
Implementation *implementation_;
public:
Abstraction(Implementation *implementation) : implementation_(implementation) { }
virtual string Operation() const {
return "Abstraction: Base operation with:\n" + this->implementation_->OperationImplementation();
}
virtual ~Abstraction() { }
};
class ExtendedAbstraction : public Abstraction {
public:
ExtendedAbstraction(Implementation* implementation) : Abstraction(implementation) { }
string Operation() const override {
return "ExtendedAbstraction: Extended operation with:\n" + this->implementation_->OperationImplementation();
}
};
void ClientCode(const Abstraction& abstraction) {
cout << abstraction.Operation();
}
int main() {
Implementation *implementation = new ConcreteImplementationA;
Abstraction *abstraction = new Abstraction(implementation);
ClientCode(*abstraction);
cout << endl;
delete implementation;
delete abstraction;
implementation = new ConcreteImplementationB;
abstraction = new ExtendedAbstraction(implementation);
ClientCode(*abstraction);
delete implementation;
delete abstraction;
}

'C | C++ > Modern C++' 카테고리의 다른 글
| Design Pattern II_Strategy Pattern, Observer Pattern, Adapter Pattern (0) | 2022.11.13 |
|---|---|
| C++로 Java와 동일한 로직을 구현해보자! (0) | 2022.11.02 |
| [TCPL]_ 1부(prev) Tip 정리. (0) | 2022.11.01 |
| [Effective Modern C++ item 1]: template 형식 연역 규칙을 숙지하라! (0) | 2022.10.28 |
| ☆Prev. C++, Modern C++의 변화 (2) | 2022.10.28 |