c++设计模式
外观模式:为子系统中的一组接口定义一个一致的界面;外观模式提供一个高层的接口,这个接口使得这一子系统更加容易被使用;对于复杂的系统,系统为客户端提供一个简单的接口,把负责的实现过程封装起来,客户端不需要连接系统内部的细节。
以下情形建议考虑外观模式:
- 设计初期阶段,应有意识的将不同层分离,层与层之间建立外观模式。
- 开发阶段,子系统越来越复杂,使用外观模式提供一个简单的调用接口。
- 一个系统可能已经非常难易维护和扩展,但又包含了非常重要的功能,可以为其开发一个外观类,使得新系统可以方便的与其交互。
优点:
- 实现了子系统与客户端之间的松耦合关系。
- 户端屏蔽了子系统组件,减少了客户端所需要处理的对象数据,使得子系统使用起来更方便容易。
- 更好的划分了设计层次,对于后期维护更加的容易。
1,运行效果
2,代码示例
#include <iostream>
#include <thread>
#include <mutex>
#include <unistd.h>
// define data struct for multi thread access.
class Data {
private:
int m_data = 0;
std::mutex m_mutex;
public:
void data(int data) {
std::lock_guard<std::mutex> guard(m_mutex);
m_data=data;
};
int data() {
std::lock_guard<std::mutex> guard(m_mutex);
return m_data;
}
// reloading the preposition incremental operator
inline Data &operator++() { ++m_data; return *this;};
// reloading the postposition incremental operator
//inline Data operator++(int) {Data tmp = *this; ++m_data; return tmp;};
//due to the mutex lock copy constructor to delete,so this function can't be implemented.
};
class Thread {
protected:
bool m_run_flag = true;
std::thread m_thread;
Data &m_data;
virtual void run() = 0;
public:
Thread(Data &data) : m_data(data) {};
~Thread() {m_run_flag = false;};
void startThread() {
m_run_flag = true;
m_thread = std::thread(&Thread::run, this);
m_thread.detach();
};
void stopThread() {m_run_flag = false;};
};
//abstract module class, provide the interface.
class Control {
public:
virtual void start() = 0;
virtual void stop() = 0;
virtual ~Control() {};
};
//the first child module, producer component.
class Producer : public Control, Thread {
public:
using Thread::Thread;
void start() override {startThread();};
void stop() override {stopThread();};
private:
void run() override {
while(m_run_flag) {
++m_data;
std::cout << "producer:" << m_data.data() << std::endl;
std::cout.flush();
sleep(1);
}
};
};
//the second child module, consumer component.
class Consumer : public Control, Thread {
public:
using Thread::Thread;
void start() override {startThread();};
void stop() override {stopThread();};
private:
void run() override {
while(m_run_flag) {
std::cout << "consumer:" << m_data.data() << std::endl;
std::cout.flush();
sleep(1);
}
};
};
// systerm class, for the client to call.
class Systerm {
public:
Systerm() {m_producer = new Producer(m_data); m_consumer = new Consumer(m_data);};
~Systerm() {delete m_producer; delete m_consumer;};
void start() {m_producer->start(); m_consumer->start();};
void stop() {m_producer->stop(); m_consumer->stop();};
private:
Data m_data;
Producer *m_producer;
Consumer *m_consumer;
};
int main() {
Systerm systerm;
systerm.start();
sleep(5);
systerm.stop();
return 0;
}