In modern software design, using composition (via the Bridge pattern) instead of inheritance is often considered a better approach, particularly when working with flexible, scalable systems. The Bridge pattern is a structural design pattern that decouples an abstraction from its implementation, allowing the two to vary independently. This pattern promotes composition by separating the interface from the implementation, which solves many problems associated with inheritance.
Here is the code of Bridge pattern implemented in Rust...
trait Color {
fn new(&self) {
}
fn get_name(&self) -> String;
}
struct Red;
struct Black;
impl Color for Red {
fn new(&self) {
println!("The color is Black");
}
fn get_name(&self) -> String {
"Red".to_string()
}
}
impl Color for Black {
fn new(&self) {
println!("The color is Black");
}
fn get_name(&self) -> String {
"Black".to_string()
}
}
trait Gear {
fn new(&self){
}
fn get_name(&self) -> String;
}
struct AutoGear;
struct ManualGear;
impl Gear for AutoGear {
fn new(&self){
println!("The gear is AutoGear");
}
fn get_name(&self) -> String {
"AutoGear".to_string()
}
}
impl Gear for ManualGear {
fn new(&self){
println!("The gear is Manual Gear");
}
fn get_name(&self) -> String {
"ManualGear".to_string()
}
}
trait Vehicle {
fn set_color(&mut self, color : Box<dyn Color>) {}
fn set_gear (&mut self, gear : Box<dyn Gear>) {}
fn display_attributes(&self) { }
}
#[derive()]
struct SmallCar{
color: Box<dyn Color>,
gear: Box<dyn Gear>,
}
#[derive()]
struct Truck{
color: Box<dyn Color>,
gear: Box<dyn Gear>,
}
impl Vehicle for SmallCar {
fn set_color(&mut self, color : Box<dyn Color>) {
self.color = color;
}
fn set_gear(&mut self, gear : Box<dyn Gear>) {
self.gear = gear;
}
fn display_attributes(&self) {
println!("The vehicle color is {:?}", self.color.get_name());
println!("The vehicle gear is {:?}", self.gear.get_name());
}
}
impl Vehicle for Truck {
fn set_color(&mut self, color : Box<dyn Color>) {
self.color = color;
}
fn set_gear(&mut self, gear : Box<dyn Gear>) {
self.gear = gear;
}
fn display_attributes(&self) {
println!("The vehicle color is {:?}", self.color.get_name());
println!("The vehicle gear is {:?}", self.gear.get_name());
}
}
fn main() {
let color = Box::new(Red);
let gear = Box::new(AutoGear);
let truck = Truck {
color: color, gear:gear,
};
truck.display_attributes();
}