Codementor Events

Design Patterns in Rust: Proxy

Published Apr 03, 2023

The proxy pattern is a very useful design pattern. The basic function is to make sure that a caller has no direct acces to the instance of an object but rather goes through another class which does have that access.

I know this all sounds rather cryptic, so maybe a diagram will help here:

proxy_new_correct.png

This could be the diagram for a mobility service, albeit very much simplified.

So what do we see here?

  1. A Drivable interface, this could be trait in Rust. This trait has exactly one method: drive(int instance).
  2. Two classes: Car and Bicycle, both of which implement the Drivable trait.
  3. A concrete VehicleProxy class, which implements the Drivable interface, but which also holds a concrete object which implements the Drivable trait.
  4. A concrete VehicleManager class, which holds the instance of the VehicleProxy. This class has no knowledge of the exact kind of vehicle that will be driven, nor of any of the implementation details.

This pattern can be very useful in some cases:

  1. If you want to control access to the concrete class.
  2. If you want to have conditional asccess to the concrete classes. In this particular example, the VehicleProxy class could also get the age of the driver as a parameter. If the driver is younger than 18, he or she is not allowed to drive a car, for example.

Open a terminal in the directory you want to use and type:

cargo new proxy_pattern

This will create the skeleton of a Rust-project. Open this in your favourite IDE, I usually use Visual Studio Code.

We will go through the implementation step by step. First open main.rs, where we will define the trait:

pub trait Drivable {
    fn drive(&self,distance:u32);
}

This trait defines one method, drive with two parameters:

  1. &self refers to the implementing struct
  2. distance is simply the distance.

Now it is time to define and implement the Car struct:

pub struct Car {

}

impl Drivable for Car {
    fn drive(&self,distance: u32) {
        println!("I drove {} kilometres in my car",distance);
    }
}

This seems quite straightforward:

  1. We define a Car struct. Since we have no other properties for this struct, the struct is empty
  2. We define an implementation of the Drivable interface on the struct. The method does nothing more than just print a message.

Now we do the same for Bicycle:

pub struct Bicycle {

}

impl Drivable for Bicycle {
    fn drive(&self,distance: u32) {
        println!("I drove {} kilometres on my bicycle",distance);
    }
}

Again, we do the same thing here:

  1. We define a Bicycle struct. Since we have no other properties for struct, the struct is empty.
  2. We define an implementation of the Drivable interface on the struct. The method again does nothing more than just print a message.

It is now time to define the VehicleProxy:

pub struct VehicleProxy {
    pub real_subject: Box<dyn Drivable+'static>
}

impl Drivable for VehicleProxy {
    fn drive(&self,distance: u32) {
        self.real_subject.drive(distance);
    }
}

This code warrants some explanation:

  1. The real_subject field is a Box, because the size is not known at compile time.
  2. In the Box generic definition we see two things:
  3. dyn Drivable: because Drivable is a trait, method calls to it will be dynamically dispatched.
  4. Then we see a lifetime specification: ‘static. This means that this field lives for the entire running of the program (that is according to the documentation)
  5. In the implementation part, we see that the drive method is called on the real_subject.

If you have trouble understanding this, please use the rust-documentation. Furthermore the compiler is extremely helpful..

Now it is time to code the VehicleManager:

pub struct VehicleManager {    
    pub vehicle_proxy: Box<VehicleProxy>
}

impl Drivable for VehicleManager {
    fn drive(&self,distance: u32) {
        self.vehicle_proxy.drive(distance);
    }
}

Also some explanation is needed here:

  1. Since we do not know to which class the VehicleProxy will refer to, the size is unknown at compiletime, so we use the Box again
  2. Notice that the drive method is called on the vehicle_proxy field.

Now to put it all to the test:

fn main() {
    let my_vehicle = Box::new(Bicycle {});

    let my_proxy = Box::new(VehicleProxy {
        real_subject: my_vehicle,
    });

    let my_vehicle_manager = Box::new(VehicleManager {
        vehicle_proxy: my_proxy,
    });

    my_vehicle_manager.drive(20);
}

Line by line:

  1. Instantiate a Box-object containing a Bicycle struct.
  2. Instatiate a Box-object, containing the Bicycle struct.
  3. Instatiate a Box-object containing a VehicleManager struct.
  4. Now call the drive-method on the my_vehicle_manager variable.

Save this file, and type:

cargo run

in your terminal. You should see: I drove 20 kilometres on my bicycle as the output.

I am not yet a very experienced Rust-programmer (I have 25+ years experience developing in other languages), and I must say I found Rust to be quite joy to use. The documentation is very clear, and the compiler is extremely helpful. I learnt a lot from programming this little example.

Discover and read more posts from Iede Snoek
get started