포맷터의 공통 인터페이스를 만들고 싶습니다. 입력기를 사용하여 목적에 따라 형식을 지정합니다.빈 구조체 구현을 반환하는 팩토리 클래스 만들기
현재 Formatter 구현을 포함하는 Box를 반환합니다 (결과로 래핑 됨). 그러나 이것이 이것이 최선의 방법이라고 생각하지 않습니다. Formatter 구현은 빈 구조체이므로 Box에 힙 메모리를 할당하는 것은 의미가 없습니다.
pub trait Formatter {
fn format_information(&self, information: Result<Information, Error>) -> Result<String, Error>;
fn format_information_collection(&self, information: InformationCollection) -> Result<String, Error>;
}
pub struct JsonFormatter;
impl Formatter for JsonFormatter {...}
pub struct XmlFormatter;
impl Formatter for XmlFormatter {...}
// Factory to create a formatter
pub struct Factory;
impl Factory {
pub fn get_formatter(format: &str) -> Result<Box<Formatter>, Error> {
match format {
"json" => Ok(Box::new(JsonFormatter {})),
"xml" => Ok(Box::new(XmlFormatter {})),
_ => Err(Error::new(format!("No formatter found for format {}", format)))
}
}
}
// Use the factory
let formatter_box = Factory::get_formatter(format).unwrap();
let formatter = &*formatter_box as &Formatter;
녹에서 올바른 방법은 무엇입니까?
답장을 보내 주셔서 감사합니다. 나는 많이 배웠다. 나는 Rust로 시작하고 내 workday 언어는 PHP 다. :) – cundd