我正在编写一个离散事件模拟器,用于模拟过程,交换事件。流程是trait流程的实现,并且存储在仿真类中,该类告诉它们何时处理事件。
一个仿真可以只包含一种类型的进程,也可以包含不同类型的进程。这就是为什么我需要能够自由选择动态进程的原因。
我现在用盒子来做。使用模拟的每个代码都需要创建方框,并将创建的对象放入方框中。
trait Process {
// methods
fn start();
fn process_event();
}
struct Simulation {
processes: Vec<dyn Process>
}
impl Simulation {
fn add_process(&mut self, p: Box<dyn Process>) {
processes.push(p);
}
fn run() {
// calls process_event on processes, based on simulation logic
}
}
我最大的问题是,在某些情况下,这些过程需要有自我引用。然后我需要用Pin或OwningRef替换盒子,我不想有每一个可能的模拟,创建一个Pin或OwningRef。所以,我想要某种通用参数来告诉模拟使用不同的类的盒子。
一个好的扩展应该是完全不需要动态调度,并且模拟包含实际的进程类型,而不是泛型。
所以,我想要像-Simulation<P> where P is either a Process or Deref<Process>
.
通用Simulation
的两种变体都是可能的。
- 包含指向进程(playground)的智能指针:
trait Process {}
struct P {}
impl Process for P {}
struct Simulation<T: std::ops::Deref<Target = dyn Process> + Sized> {
processes: Vec<T>
}
impl<T: std::ops::Deref<Target = dyn Process> + Sized> Simulation<T> {
fn add_process(&mut self, p: T) {
self.processes.push(p);
}
fn run(&self) {
// calls process_event on processes, based on simulation logic
}
}
fn main() {
let mut s: Simulation<Box<dyn Process>> = Simulation { processes: vec![] };
s.add_process(Box::new(P {}));
s.run();
let mut s: Simulation<std::rc::Rc<dyn Process>> = Simulation { processes: vec![] };
s.add_process(std::rc::Rc::new(P {}));
s.run();
}
- 包含实际进程类型(playground):
trait Process {}
struct P {}
impl Process for P {}
struct P2 {}
impl Process for P2 {}
struct Simulation<T: Process> {
processes: Vec<T>
}
impl<T: Process> Simulation<T> {
fn add_process(&mut self, p: T) {
self.processes.push(p);
}
fn run(&self) {
// calls process_event on processes, based on simulation logic
}
}
fn main() {
let mut s: Simulation<P> = Simulation { processes: vec![] };
s.add_process(P {});
s.run();
let mut s: Simulation<P2> = Simulation { processes: vec![] };
s.add_process(P2 {});
s.run();
}
- 您甚至可以有一种类型的模拟,包含不同类型的进程(游乐场):
trait Process {}
struct P {}
impl Process for P {}
struct P2 {}
impl Process for P2 {}
struct Simulation {
processes: Vec<Box<dyn Process>>
}
impl Simulation {
fn add_process<T: Process + 'static>(&mut self, p: T) {
self.processes.push(Box::new(p));
}
fn run(&self) {
// calls process_event on processes, based on simulation logic
}
}
fn main() {
let mut s: Simulation = Simulation { processes: vec![] };
s.add_process(P {});
s.run();
let mut s: Simulation = Simulation { processes: vec![] };
s.add_process(P2 {});
s.run();
}