A REST API demonstrating the Factory Pattern in Rust with an extensible parser registry.
Before (Without Factory):
// If-else hell.
let parser: Box<dyn Parser> = if format == "json" {
Box::new(JsonParser::new())
} else if format == "xml" {
Box::new(XmlParser::new())
} else if format == "yaml" {
Box::new(YamlParser::new())
} // ... duplicated 15+ times!After (With Factory):
// Clean, one line.
let parser = ParserFactory::create(format)?;- Factory Pattern: Centralized parser creation.
- Extensible Registry: Add parsers without modifying factory.
- Auto-detection: Detect format from filename.
- Clean Abstraction: All parsers implement DocumentParser trait.
- Easy Testing: Mock parsers easily.
- JSON (.json, .jsonl)
- XML (.xml, .xhtml)
- YAML (.yaml, .yml)
- CSV (.csv, .tsv)
- Markdown (.md, .markdown)
cargo runServer starts on http://localhost:3000
curl -X POST http://localhost:3000/parse \
-H "Content-Type: application/json" \
-d '{
"content": "{\"name\": \"test\", \"value\": 42}",
"format": "json"
}'curl -X POST http://localhost:3000/parse \
-H "Content-Type: application/json" \
-d '{
"content": "name: test\nvalue: 42",
"filename": "data.yaml"
}'curl http://localhost:3000/parsers- Create parser implementing
DocumentParsertrait. - Register in
registry.rs - Done! No changes to factory or handlers needed!
// 1. Implement parser.
pub struct TomlParser;
impl DocumentParser for TomlParser { /* ... */ }
// 2. Register.
registry.register("toml".to_string(), Arc::new(TomlParser::new()));