Skip to content

Instantly share code, notes, and snippets.

@sumnjc
Created April 20, 2015 00:17
Show Gist options
  • Save sumnjc/ab329c647af05f10ad3b to your computer and use it in GitHub Desktop.
Save sumnjc/ab329c647af05f10ad3b to your computer and use it in GitHub Desktop.
Template Method Pattern
#include <iostream>
#include <string>
using namespace std;
class CMakeDrink{
private:
virtual void make()=0;
virtual void addOption()=0;
void boilwater() {cout << "물을 끓인다" << endl;}
void tocup() {cout << "컵에 따른다" << endl;}
public:
virtual ~CMakeDrink() {}
void processing() // 제어는 부모 클래스에서 담당하고 상세구현은 각각의 파생클래스에서 처리 => DIP
{
boilwater();
addOption(); // 제어의 역전 (DIP)
make();
tocup();
}
};
// 부모 클래스에서 행해지는 전체 제어에는 변경이 없이, 새로운 기능은 파생클래스의 확장으로 가능. => OCP
class CMakeCoffee:public CMakeDrink
{
private:
void make() override {cout << "커피를 만든다." << endl;}
void addOption() override {cout <<"설탕을 넣는다." << endl;}
public:
~CMakeCoffee() {}
};
class CMakeRedtee:public CMakeDrink
{
private:
void make() override {cout << "홍차를 만든다." << endl;}
void addOption() override {cout <<"레몬을 넣는다." << endl;}
public:
~CMakeRedtee() {}
};
int main()
{
CMakeDrink* coffee = new CMakeCoffee; // LSP 원칙 만족. 부모클래스 변수에 자식 객체 대입해도 이상 없음.
CMakeDrink* redtee = new CMakeRedtee;
coffee->processing();
redtee->processing();
delete coffee;
delete redtee;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment