It's truly said that if you teach a person, actually two people learn.
As a guru of my young son, Ridit, I taught him many design patterns and he implemented them in three different languages.
Here's his discussion on Adaptor Design Pattern.
Please go through his explanation.
use std::io;
trait IWeatherFinder {
fn get_temperature(&self, city_name : &str)-> i32;
}
struct WeatherFinder{}
impl IWeatherFinder for WeatherFinder{
fn get_temperature(&self, city_name : &str) -> i32{
if (city_name.trim().eq("Kolkata".trim())){
40
}
else{
println!("Unknown City Name...Could not read temperature");
-273
}
}
}
trait iWeatherFinderClient {
fn get_temperature (&self, city_pincode : i32)->i32;
}
struct WeatherAdapter{}
impl WeatherAdapter {
fn get_city_name (&self, pincode : i32) -> &str {
if pincode == 700078 {
"Kolkata".trim()
}
else {
"UnknownCity"
}
}
fn get_temperature (&self, pincode : i32)-> i32 {
let city_name = self.get_city_name(pincode);
let weatherfinder : WeatherFinder = *Box::new(WeatherFinder{});
weatherfinder.get_temperature(city_name)
}
}
fn main() {
println!("Enter pin code");
let mut pincode = String::new();
io::stdin().read_line(&mut pincode).expect("Failed to read line");
let pin_code: i32 = pincode.trim().parse().expect("Input not an integer");
let weatheradapter = WeatherAdapter{};
let temperature: i32 = weatheradapter.get_temperature(pin_code);
println!("The temparature is {} degree celcius", temperature);
}
Output:
Enter pin code
700078
The temperature is 40 degree celcius
No comments:
Post a Comment