roopes_core/patterns/observer/mod.rs
1//!
2#![cfg_attr(feature = "doc-images",
3 cfg_attr(
4 all(),
5 doc = ::embed_doc_image::embed_image!(
6 "observer-diagram",
7 "src/patterns/observer/observer.svg"
8)))]
9//! Contains types which implement the "Observer"
10//! pattern, in which a single object is used to
11//! delegate notifications to a group of dynamic
12//! listening object.
13//!
14//! ![observer diagram][observer-diagram]
15
16pub mod hash_subject;
17pub mod vec_subject;
18
19use crate::prelude::*;
20pub use hash_subject::HashSubject;
21pub use vec_subject::VecSubject;
22
23#[cfg(test)]
24mod tests;
25
26/// An object which notifies some group of
27/// [`Observer`]s. When it is notified,
28/// all the listeners are notified.
29pub trait Subject
30{
31 /// Triggers the [`Observer`]s corresponding
32 /// `notify` implementations.
33 fn notify(&self);
34}
35
36/// An object notified by a [`Subject`].
37pub trait Observer
38{
39 /// Executes some arbitrary block in the
40 /// implementing object.
41 fn notify(&self);
42}
43
44/// Allows [`Observer`]s to be added to the
45/// implementing [`Subject`].
46pub trait AttachableSubject<O>: Subject
47where
48 O: Observer,
49{
50 /// Adds the [`Observer`] to the list of
51 /// elements notified when the [`Subject`]
52 /// is notified.
53 fn attach(
54 &mut self,
55 attach_observer: O,
56 );
57}
58
59/// Allows [`Observer`]s to be removed from the
60/// implementing [`Subject`].
61pub trait DetachableSubject<O, E>: Subject
62where
63 O: Observer,
64{
65 /// Detaches the given [`Observer`] from the
66 /// [`Subject`] so it would no
67 /// longer receive notifications.
68 ///
69 /// # Errors
70 /// E: The error that occurred during
71 /// detachment.
72 fn detach(
73 &mut self,
74 detach_observer: &O,
75 ) -> Result<(), E>;
76}
77
78/// Exposes the [`Observer`] and [`Subject`] types
79/// at the library level.
80pub mod prelude
81{
82 pub use super::{
83 AttachableSubject,
84 DetachableSubject,
85 Observer,
86 Subject,
87 };
88}