Skip to content

Commit

Permalink
adapter
Browse files Browse the repository at this point in the history
  • Loading branch information
lpxxn committed Feb 27, 2020
1 parent 60af52e commit 20ed582
Show file tree
Hide file tree
Showing 2 changed files with 77 additions and 1 deletion.
8 changes: 7 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,14 @@
| [Singleton](/creational/singleton.rs) | Restricts instantiation of a type to one object ||



## Behavioral Patterns
| Pattern | Description | Status |
|:-------:|:----------- |:------:|
| [Strategy](/behavioral/strategy.rs) | Enables an algorithm's behavior to be selected at runtime ||


## Structural Patterns

| Pattern | Description | Status |
|:-------:|:----------- |:------:|
| [Adapter](/structural/adapter.rs) | allows objects with incompatible interfaces to collaborate. ||
70 changes: 70 additions & 0 deletions structural/adapter.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
use std::rc::Rc;

// The Target defines the domain-specific interface used by the client code.
trait Target {
fn get_request(&self) -> String {
String::from("Target: The default target's behavior.")
}
}

struct DefaultTarget;
impl Target for DefaultTarget {}

// The Adaptee contains some useful behavior, but its interface is
// incompatible with the existing client code. The Adaptee needs some
// adaptation before the client code can use it.
struct Adaptee {
req_str: String,
}

impl Adaptee {
fn new(s: String) -> Adaptee {
Adaptee{
req_str: s,
}
}
fn specific_request(&self) -> String {
format!("specific request: {}", self.req_str)
}
}

// The Adapter makes the Adaptee's interface compatible with the Target's
// interface.
struct Adapter {
adaptee: Rc<Adaptee>,
}

impl Adapter {
fn new(a: Rc<Adaptee>) -> Adapter {
Adapter {
adaptee: a,
}
}
}

impl Target for Adapter {
fn get_request(&self) -> String {
format!("Adapter: {}", self.adaptee.specific_request())
}
}

// The client code supports all classes that follow the Target trait.
struct Client;
impl Client {
fn clinet_code<T: Target>(target: T) {
println!("{}", target.get_request());
}
}


fn main() {
println!("Client: I can work just fine with the Target objects:");
Client::clinet_code(DefaultTarget{});
let adaptee = Rc::new(Adaptee::new("hello world".to_string()));
println!("Client: The Adaptee class has a weird interface. See, I don't understand it:");
println!("Adaptee: {}", adaptee.specific_request());

println!("Client: But I can work with it via the Adapter:");
let adapter = Adapter::new(adaptee);
Client::clinet_code(adapter);
}

0 comments on commit 20ed582

Please sign in to comment.