Autumn SALE
어댑터

러스트로 작성된 어댑터

어댑터는 구조 디자인 패턴이며, 호환되지 않는 객체들이 협업할 수 있도록 합니다.

어댑터는 두 객체 사이의 래퍼 역할을 합니다. 하나의 객체에 대한 호출을 캐치하고 두 번째 객체가 인식할 수 있는 형식과 인터페이스로 변환합니다.

Adapter in Rust

In this example, the trait SpecificTarget is incompatible with a call function which accepts trait Target only.

fn call(target: impl Target);

The adapter helps to pass the incompatible interface to the call function.

let target = TargetAdapter::new(specific_target);
call(target);

adapter.rs

use crate::{adaptee::SpecificTarget, Target};

/// Converts adaptee's specific interface to a compatible `Target` output.
pub struct TargetAdapter {
    adaptee: SpecificTarget,
}

impl TargetAdapter {
    pub fn new(adaptee: SpecificTarget) -> Self {
        Self { adaptee }
    }
}

impl Target for TargetAdapter {
    fn request(&self) -> String {
        // Here's the "adaptation" of a specific output to a compatible output.
        self.adaptee.specific_request().chars().rev().collect()
    }
}

adaptee.rs

pub struct SpecificTarget;

impl SpecificTarget {
    pub fn specific_request(&self) -> String {
        ".tseuqer cificepS".into()
    }
}

target.rs

pub trait Target {
    fn request(&self) -> String;
}

pub struct OrdinaryTarget;

impl Target for OrdinaryTarget {
    fn request(&self) -> String {
        "Ordinary request.".into()
    }
}

main.rs

mod adaptee;
mod adapter;
mod target;

use adaptee::SpecificTarget;
use adapter::TargetAdapter;
use target::{OrdinaryTarget, Target};

/// Calls any object of a `Target` trait.
///
/// To understand the Adapter pattern better, imagine that this is
/// a client code, which can operate over a specific interface only
/// (`Target` trait only). It means that an incompatible interface cannot be
/// passed here without an adapter.
fn call(target: impl Target) {
    println!("'{}'", target.request());
}

fn main() {
    let target = OrdinaryTarget;

    print!("A compatible target can be directly called: ");
    call(target);

    let adaptee = SpecificTarget;

    println!(
        "Adaptee is incompatible with client: '{}'",
        adaptee.specific_request()
    );

    let adapter = TargetAdapter::new(adaptee);

    print!("But with adapter client can call its method: ");
    call(adapter);
}

Output

A compatible target can be directly called: 'Ordinary request.'
Adaptee is incompatible with client: '.tseuqer cificepS'
But with adapter client can call its method: 'Specific request.'

다른 언어로 작성된 어댑터

C#으로 작성된 어댑터 C++로 작성된 어댑터 Go로 작성된 어댑터 자바로 작성된 어댑터 PHP로 작성된 어댑터 파이썬으로 작성된 어댑터 루비로 작성된 어댑터 스위프트로 작성된 어댑터 타입스크립트로 작성된 어댑터