Day11:How to implement "Template Method" design pattern - 100DayOfRust

bitecode

BC

Posted on November 29, 2019

Day11:How to implement "Template Method" design pattern - 100DayOfRust

The implementation of "template method" design pattern usually utilizes a base class and a derived class: The base class will define a workflow and the derived class override method in the workflow.

However, Rust doesn't have "inheritance". While I am not sure if this is a correct way to do, but I found that we can use the trait feature to implement the same thing.

First we define a BaseHandler trait to define the workflow: in the get function we call authorized and do_get function. Then our "derived" class UserHandler will implement this trait with overriding those 2 methods.

trait BaseHandler {
    fn authorized(&self) -> bool {
        false
    }

    fn get(&self) -> String {
        if !self.authorized() {
            return "403 Forbidden".to_string();
        }
        println!("Do some basic work");
        // handle rest work to do_get
        self.do_get()
    }

    fn do_get(&self) -> String;
}

struct UserHandler;

impl BaseHandler for UserHandler {
    fn authorized(&self) -> bool {
        true
    }

    fn do_get(&self) -> String {
        "Processed by User handler".to_string()
    }
}

fn main() {
    let handler = UserHandler {};
    println!("{}", handler.get());
}
Enter fullscreen mode Exit fullscreen mode

Result:

Do some basic work
Processed by User handler
Enter fullscreen mode Exit fullscreen mode
💖 💪 🙅 🚩
bitecode
BC

Posted on November 29, 2019

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related