main
Andrey Pilipenko 9 months ago
parent f7c613f03b
commit c4eb3b4753

@ -0,0 +1,45 @@
{
// Используйте IntelliSense, чтобы узнать о возможных атрибутах.
// Наведите указатель мыши, чтобы просмотреть описания существующих атрибутов.
// Для получения дополнительной информации посетите: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"type": "lldb",
"request": "launch",
"name": "Debug executable 'Manager'",
"cargo": {
"args": [
"build",
"--bin=Manager",
"--package=Manager"
],
"filter": {
"name": "Manager",
"kind": "bin"
}
},
"args": [],
"cwd": "${workspaceFolder}"
},
{
"type": "lldb",
"request": "launch",
"name": "Debug unit tests in executable 'Manager'",
"cargo": {
"args": [
"test",
"--no-run",
"--bin=Manager",
"--package=Manager"
],
"filter": {
"name": "Manager",
"kind": "bin"
}
},
"args": [],
"cwd": "${workspaceFolder}"
}
]
}

@ -0,0 +1,8 @@
[package]
name = "Manager"
version = "0.1.0"
edition = "2021"
[dependencies]
postgres = "*"
lazy_static = "*"

@ -0,0 +1,99 @@
use std::collections::HashMap;
use std::sync::Mutex;
use lazy_static::lazy_static;
use crate::traits::{Action, ActionType};
type RecieverID = i32;
// Трейт IReciever (аналог интерфейса в C++)
pub trait IReciever {
fn id(&self) -> RecieverID;
fn recieve(&self, action: Action);
}
// Реализация Reciever
pub struct Reciever {
id: RecieverID,
}
impl Reciever {
pub fn new(id: RecieverID) -> Self {
Reciever { id }
}
}
impl IReciever for Reciever {
fn id(&self) -> RecieverID {
self.id
}
fn recieve(&self, action: Action) {
println!("Reciever: action id={} action data={}", action.typ, action.payload);
}
}
// Глобальные статические переменные для subscriptions и actions
lazy_static! {
static ref SUBSCRIPTIONS: Mutex<HashMap<ActionType, HashMap<RecieverID, Box<dyn IReciever + Send>>>> =
Mutex::new(HashMap::new());
static ref ACTIONS: Mutex<HashMap<ActionType, Action>> = Mutex::new(HashMap::new());
}
// Трейт IDispatcher
pub trait IDispatcher {
fn subscribe(&self, action_id: ActionType, reciever: Box<dyn IReciever + Send>);
fn unsubscribe(&self, action_id: ActionType, reciever_id: RecieverID);
fn proccess(&self);
fn send(&self, action: Action);
fn erase(&self, action_id: ActionType);
}
// Реализация Dispatcher
pub struct Dispatcher;
impl Dispatcher {
pub fn new() -> Self {
Dispatcher
}
}
impl IDispatcher for Dispatcher {
fn subscribe(&self, action_id: ActionType, reciever: Box<dyn IReciever + Send>) {
SUBSCRIPTIONS
.lock()
.unwrap()
.entry(action_id)
.or_insert_with(HashMap::new)
.insert(reciever.id(), reciever);
}
fn unsubscribe(&self, action_id: ActionType, reciever_id: RecieverID) {
if let Some(recievers) = SUBSCRIPTIONS.lock().unwrap().get_mut(&action_id) {
recievers.remove(&reciever_id);
}
}
fn proccess(&self) {
let mut actions = ACTIONS.lock().unwrap();
let subscriptions = SUBSCRIPTIONS.lock().unwrap();
let actions_clone = actions.clone(); // Клонируем actions для итерации
for (action_id, action) in actions_clone {
if let Some(recievers) = subscriptions.get(&action_id) {
for reciever in recievers.values() {
reciever.recieve(action.clone());
}
actions.remove(&action_id); // Удаляем обработанное действие
}
}
}
fn send(&self, action: Action) {
ACTIONS.lock().unwrap().insert(action.typ, action);
}
fn erase(&self, action_id: ActionType) {
ACTIONS.lock().unwrap().remove(&action_id);
}
}

@ -0,0 +1,15 @@
use crate::traits;
pub struct Listener {
id: ListenerID,
}
impl IListener for Listener {
fn id(&self) -> ListenerID {
self.id
}
fn listen(&self, store: IStore) {
println!("listen getState: ", store.getState());
}
}

@ -0,0 +1,35 @@
mod traits;
mod dispatcher;
mod store;
use dispatcher::{Dispatcher, IDispatcher, Reciever, IReciever};
use traits::Action;
use store::Store;
fn main() {
let s = Store::new();
let d1 = Dispatcher::new();
let r1 = Box::new(Reciever::new(1)) as Box<dyn IReciever + Send>;
let r2 = Box::new(Reciever::new(2)) as Box<dyn IReciever + Send>;
let a1 = Action {
typ: 1,
payload: "11111".to_string(),
};
let a2 = Action {
typ: 2,
payload: "22222".to_string(),
};
d1.subscribe(a1.typ, r1);
d1.subscribe(a2.typ, r2);
d1.send(a1);
d1.send(a2);
let d2 = Dispatcher::new();
d2.proccess(); // Теперь d2 работает с общими данными
}

@ -0,0 +1,29 @@
use crate::traits::{Action, IListener, State, IStore};
use crate::dispatcher::{IDispatcher,Dispatcher};
pub struct Store {
state: State,
dispatcher: Box<dyn IDispatcher + Send>
}
impl Store {
pub fn new() -> Self {
Store{
state: State {},
dispatcher:Box::new(Dispatcher::new())
}
}
}
impl IStore for Store {
fn getState(&self) -> State {
return self.state.clone();
}
fn dispatch(&self, action: Action) {
}
fn subscribe(&self, listener: Box<dyn IListener + Send>){
}
fn unsubscribe(&self, listener: Box<dyn IListener + Send>){
}
}

@ -0,0 +1,26 @@
pub type ListenerID = i32;
pub type ActionType = i32;
pub type Payload = String;
#[derive(Clone)]
pub struct Action {
pub typ: ActionType,
pub payload: Payload,
}
#[derive(Clone)]
pub struct State {
}
pub trait IListener {
fn id(&self) -> ListenerID;
fn listen(&self, store: Box<dyn IListener + Send>);
}
pub trait IStore {
fn getState(&self) -> State;
fn dispatch(&self, action: Action);
fn subscribe(&self, listener: Box<dyn IListener + Send>);
fn unsubscribe(&self, listener: Box<dyn IListener + Send>);
}
Loading…
Cancel
Save