Observer.hpp 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. /**
  2. * @file artis/observer/Observer.hpp
  3. * @author See the AUTHORS file
  4. */
  5. /*
  6. * Copyright (C) 2012-2019 ULCO http://www.univ-littoral.fr
  7. *
  8. * This program is free software: you can redistribute it and/or modify
  9. * it under the terms of the GNU General Public License as published by
  10. * the Free Software Foundation, either version 3 of the License, or
  11. * (at your option) any later version.
  12. *
  13. * This program is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. * GNU General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU General Public License
  19. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  20. */
  21. #ifndef ARTIS_OBSERVER_OBSERVER_HPP
  22. #define ARTIS_OBSERVER_OBSERVER_HPP
  23. #include <artis/kernel/AbstractModel.hpp>
  24. #include <artis/observer/View.hpp>
  25. #include <vector>
  26. namespace artis {
  27. namespace observer {
  28. template<typename U, typename V>
  29. class Observer {
  30. public:
  31. typedef std::map<std::string, View<U, V>*> Views;
  32. Observer(const artis::kernel::AbstractModel<U, V>* model)
  33. :
  34. _model(model) { }
  35. virtual ~Observer()
  36. {
  37. for (typename Views::iterator it = _views.begin(); it != _views.end();
  38. ++it) {
  39. delete it->second;
  40. }
  41. }
  42. void attachView(const std::string& name, View<U, V>* view)
  43. {
  44. _views[name] = view;
  45. view->attachModel(_model);
  46. }
  47. Views* cloneViews() const
  48. {
  49. Views* v = new Views();
  50. for (typename Views::const_iterator it = _views.begin();
  51. it != _views.end(); ++it) {
  52. (*v)[it->first] = it->second->clone();
  53. }
  54. return v;
  55. }
  56. const View<U, V>& view(const std::string& name) const { return *_views.find(name)->second; }
  57. const Views& views() const { return _views; }
  58. void init() { }
  59. void observe(double t)
  60. {
  61. for (typename Views::iterator it = _views.begin(); it != _views.end();
  62. ++it) {
  63. it->second->observe(t);
  64. }
  65. }
  66. private:
  67. const artis::kernel::AbstractModel<U, V>* _model;
  68. Views _views;
  69. };
  70. }
  71. }
  72. #endif