design_patterns.cpp 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. #include <mutex>
  2. #include <stdexcept>
  3. void do()
  4. {
  5. static std::mutex mutex;
  6. std::lock_guard<std::mutex> lock(mutex);
  7. std::ofstream file("file.txt");
  8. if (!file.is_open())
  9. throw std::runtime_error("Can't open file!");
  10. file << "Add some text!";
  11. } // if exception is thrown, we skip the writing to file and the scope closes, releasing all objects
  12. // State Pattern
  13. class Context {
  14. public:
  15. void request() {}
  16. };
  17. class State {
  18. public:
  19. virtual void handle() {}
  20. };
  21. class RealState : public State
  22. {
  23. void handle() override { (void)(0); }
  24. };
  25. class GreatState : public State
  26. {
  27. void handle() override { (void)(0); }
  28. };
  29. // Visitor
  30. class CarElement {};
  31. class CarElementVisitor {
  32. public:
  33. };
  34. // Double-checked locking with singleton
  35. class Singleton {
  36. public:
  37. static Singleton* instance();
  38. private:
  39. Singleton() = default;
  40. static std::atomic<Singleton*> s_instance;
  41. static std::mutex s_mutex;
  42. };
  43. Singleton* Singleton::GetInstance()
  44. {
  45. Singleton* p = s_instance.load(std::memory_order_acquire);
  46. if (!p)
  47. {
  48. std::lock_guard<std::mutex> lock(s_mutex);
  49. p = s_instance.load(std::memory_order_relaxed);
  50. if (!p)
  51. {
  52. p = new Singleton();
  53. s_instance.store(p, std::memory_order_acquire);
  54. }
  55. }
  56. return p;
  57. }