mirror of
https://github.com/huihut/interview.git
synced 2026-03-13 10:02:55 +08:00
添加设计模式及例子,包括:单例、抽象工厂、适配器、桥接、观察者模式
This commit is contained in:
34
DesignPattern/SingletonPattern/README.md
Normal file
34
DesignPattern/SingletonPattern/README.md
Normal file
@@ -0,0 +1,34 @@
|
||||
# 单例模式
|
||||
|
||||
```cpp
|
||||
// 懒汉式单例模式
|
||||
class Singleton
|
||||
{
|
||||
private:
|
||||
Singleton() { }
|
||||
static Singleton * pInstance;
|
||||
public:
|
||||
static Singleton * GetInstance()
|
||||
{
|
||||
if (pInstance == nullptr)
|
||||
pInstance = new Singleton();
|
||||
return pInstance;
|
||||
}
|
||||
};
|
||||
|
||||
// 线程安全的单例模式
|
||||
class Singleton
|
||||
{
|
||||
private:
|
||||
Singleton() { }
|
||||
~Singleton() { }
|
||||
Singleton(const Singleton &);
|
||||
Singleton & operator = (const Singleton &);
|
||||
public:
|
||||
static Singleton & GetInstance()
|
||||
{
|
||||
static Singleton instance;
|
||||
return instance;
|
||||
}
|
||||
};
|
||||
```
|
||||
11
DesignPattern/SingletonPattern/Singleton.cpp
Normal file
11
DesignPattern/SingletonPattern/Singleton.cpp
Normal file
@@ -0,0 +1,11 @@
|
||||
//
|
||||
// Created by xiemenghui on 2018/7/20.
|
||||
//
|
||||
|
||||
#include <iostream>
|
||||
#include "Singleton.h"
|
||||
|
||||
void Singleton::DoSomething()
|
||||
{
|
||||
std::cout << "Singleton do something\n";
|
||||
}
|
||||
25
DesignPattern/SingletonPattern/Singleton.h
Normal file
25
DesignPattern/SingletonPattern/Singleton.h
Normal file
@@ -0,0 +1,25 @@
|
||||
//
|
||||
// Created by xiemenghui on 2018/7/20.
|
||||
//
|
||||
|
||||
#ifndef DESIGNPATTERN_SINGLETON_H
|
||||
#define DESIGNPATTERN_SINGLETON_H
|
||||
|
||||
// 单例模式
|
||||
class Singleton {
|
||||
private:
|
||||
Singleton(){}
|
||||
~Singleton(){}
|
||||
Singleton(const Singleton &);
|
||||
Singleton & operator= (const Singleton &);
|
||||
|
||||
public:
|
||||
static Singleton & GetInstance()
|
||||
{
|
||||
static Singleton instance;
|
||||
return instance;
|
||||
}
|
||||
void DoSomething();
|
||||
};
|
||||
|
||||
#endif //DESIGNPATTERN_SINGLETON_H
|
||||
15
DesignPattern/SingletonPattern/SingletonMain.h
Normal file
15
DesignPattern/SingletonPattern/SingletonMain.h
Normal file
@@ -0,0 +1,15 @@
|
||||
//
|
||||
// Created by xiemenghui on 2018/7/20.
|
||||
//
|
||||
|
||||
#ifndef DESIGNPATTERN_SINGLETONMAIN_H
|
||||
#define DESIGNPATTERN_SINGLETONMAIN_H
|
||||
|
||||
#include "Singleton.h"
|
||||
|
||||
void SingletonMain()
|
||||
{
|
||||
Singleton::GetInstance().DoSomething();
|
||||
}
|
||||
|
||||
#endif //DESIGNPATTERN_SINGLETONMAIN_H
|
||||
Reference in New Issue
Block a user