Hello.
I'm playing with the design pattern - strategy.
I wrote this example:
Rust Playground
Assumptions/Comments:
- The Converter structure is responsible for the general implementation of the program (common functions).
- A specific algorithm (strategy) is performed using the DataProcess feature.
- There will be about 4 specific algorithms.
(There is no need to create an abstraction factory?)
What else can be improved or changed?
Edit:
References:
I'd consider doing something like this, which allows static dispatch when the strategy is known at compile time:
impl<T:?Sized + DataProcess> DataProcess for Box<T> {
/* ... */
}
struct Converter<T=Box<dyn DataProcess>> {
process_behaviour: T,
}
impl<T> Converter<T> where T:DataProcess {
fn process(&self) {
// .. any common code
self.process_behaviour.process();
// .. any common code
}
fn new()->Self where T:Default { ... }
}
impl Converter {
fn new_dyn(converter_type: ConverterType) -> Converter {
/* your earlier new implementation */
}
}
1 Like
Another alternative, which uses unsized coercion. This might not be possible depending on what other fields Converter has:
struct Converter<T:?Sized = dyn DataProcess> {
process_behaviour: T,
}
impl<T:?Sized + DataProcess> Converter<T> {
fn process(&self) {
// .. any common code
self.process_behaviour.process();
// .. any common code
}
fn new(processor:T) -> Self where T: Sized
{
Converter { process_behaviour: processor }
}
fn boxed(self) -> Box<Converter> where T: Sized + 'static
{
Box::new(self)
}
}
fn main() {
println!("Process w/ static dispatch");
let c = Converter::new(Text);
c.process();
let c2 = Converter::new(Json);
c2.process();
println!("");
println!("Process w/ dynamic dispatch");
let v = vec![c.boxed(), c2.boxed()];
for dyn_c in v {
dyn_c.process()
}
}
(Playground)
1 Like
system
Closed
5
This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.