
use std::ops::{Deref, DerefMut};
// Target
trait Text {
fn get_text(&self) -> String; // Request()
}
// Adaptee
#[derive(Default)]
struct StringList { rows: Vec<String> }
impl StringList {
fn add(&mut self, value: &str) {
self.rows.push(value.to_string());
}
fn get_string(&self) -> String {
self.rows.join("\n") // SpecificRequest()
}
}
// Adapter: wraps Adaptee, "inherits" its methods via Deref.
// NOTE: Deref-based "inheritance" is a known anti-pattern in idiomatic Rust;
// shown here only to mirror class-based Adapter from OOP languages.
struct TextAdapter(StringList);
impl Deref for TextAdapter {
type Target = StringList;
fn deref(&self) -> &StringList { &self.0 }
}
impl DerefMut for TextAdapter {
// needed for add()'s &mut self
fn deref_mut(&mut self) -> &mut StringList { &mut self.0 }
}
impl Text for TextAdapter {
fn get_text(&self) -> String {
// Request() delegates to SpecificRequest()
self.get_string()
}
}
fn main() {
let mut adapter = TextAdapter(StringList::default());
adapter.add("line 1");
adapter.add("line 2");
//Output: line 1
// line 2
println!("{}", adapter.get_text());
}
| Convert the interface of a class into another interface clients expect. Adapter lets classes work together that couldn't otherwise because of incompatible interfaces. |