
싱글톤 : 인스턴스가 단 하나만 존재하도록 보장, 전역변수의 편리함을 가지면서, 생성과 수명 관리를 통제할 수 있다.
데코레이터 : 객체 코드를 수정하지 않고 런타임에 기능을 겹겹이 추가, 객체에 동적으로 새로운 책임을 추가하는 패턴
옵저버 : 한 객체의 상태가 변하면 의존하는 다른 객체들에게 자동으로 알림, 이벤트 기반 시스템의 핵심, 게임업적/UI시스템 등
#include <iostream>
template<typename T>
class Singleton {
public:
static T& GetInstance() {
static T instance;
return instance;
}
Singleton(const Singleton&) = delete;
Singleton& operator=(const Singleton&) = delete;
protected:
Singleton() {}
virtual ~Singleton() {}
};
class GameManager : public Singleton<GameManager> {
friend class Singleton<GameManager>;
private:
GameManager() {
std::cout << "GameManager 생성" << std::endl;
Score = 0;
}
public:
int Score;
void AddScore(int value) { Score += value; }
};
int main() {
GameManager::GetInstance().AddScore(100);
std::cout << "Current Score:"
<< GameManager::GetInstance().Score << std::endl;
GameManager& gm1 = GameManager::GetInstance();
GameManager& gm2 = GameManager::GetInstance();
if (&gm1 == &gm2) {
std::cout << "두 객체는 완벽히 동일한 인스턴스입니다." << std::endl;
}
return 0;
}
static T& GetInstance() : 전역 접근점static T instance : 함수 내부에 선언된 static변수는 프로그램 실행시 생성되고, 프로그램 종료될때까지 살아있음protected로 생성자와 소멸자를 감싸서 이 클래스를 상속받는 자식클래스에서는 호출할 수 있지만, 외부에서는 직접 생성할 수 없다.public Singleton<GameManager> : GameManager가 Singleton을 상속받습니다.friend 선언 : C++에서 private 멤버는 오직 자기자신만 접근할 수 있습니다.long long solution(long long n) {
long long answer = 0;
string newN = to_string(n);
sort(newN.begin(), newN.end(), greater<char>());
return stoll(newN);
}
int solution(int num) {
int answer = 0;
long long tmp = num;
if (num == 1){
return 0;
}
while (true){
if (tmp % 2 == 0){
tmp /= 2;
} else {
tmp = (tmp * 3) + 1;
}
answer++;
if (answer == 500){
return -1;
}
if (tmp == 1){
break;
}
}
return answer;
}
#include <algorithm>
string solution(vector<string> seoul) {
string answer = "";
auto it = find(seoul.begin(), seoul.end(), "Kim");
answer = "김서방은 " + to_string(it-seoul.begin()) + "에 있다";
return answer;
}
서울에서 김서방 찾기문제를 풀때 처음에 vector의 find활용방법이 헷갈렸다.
이번기회에 한번 정리해야겠다.
vector, list는 altorithm헤더의 find를 쓴다.
멤버 함수 find() : 보통 set, map, multimap, multiset, unordered_set, unordered_map에서 사용
string의 find

#include <algorithm>
using namespace std;
vector<int> solution(vector<int> arr) {
auto it = min_element(arr.begin(), arr.end());
arr.erase(arr.begin() + distance(arr.begin(), it));
if (arr.empty()){
arr.push_back(-1);
}
return arr;
}
string solution(string s) {
int len = s.length();
string tmp;
int index = s.length() / 2;
if (len % 2){
tmp = s.substr(index, 1);
} else {
tmp = s.substr(index-1, 2);
}
return tmp;
}
#include <cctype>
bool solution(string s) {
if (s.length() == 4 || s.length() == 6){
for (int i = 0; i < s.length(); i++){
if (!isdigit(s[i])){
return false;
}
}
return true;
} else{
return false;
}
}