Factory design Pattern in Rust

A Factory Pattern or Factory Method Pattern says that just define an interface or abstract class for creating an object but let the subclasses decide which class to instantiate.

In other words, subclasses are responsible to create the instance of the class. The Factory Method Pattern is also known as Virtual Constructor.

Problems solved by Factory Method :

  • Complex object creation, especially within several layers of class hierarchy
  • Usage of new() operator, causing complexity, duplication and inflexibility issues in application code
  • When the client is unauthorized to access in-detail class implementations

When to use the Factory design pattern :

  • The factory method is used when Products don't need to know how they are created.
  • We can use factory pattern where we have to create an object of any one of sub-classes depending on the data provided
  • Some or all concrete products can be created in multiple ways, or we want to leave open the option that in the future there may be new ways to create the concrete product.
trait Product {
	fn use_product(&self);

struct IDCard { owner: String, }

impl IDCard { fn new(owner: String) -> IDCard { println!("{}のカードを作ります。", owner); IDCard { owner: owner, } }
fn get_owner(&self) -> String { self.owner.clone() } }

impl Product for IDCard { fn use_product(&self) { println!("{}のカードを使います", self.owner); } }

trait Factory { type Object; fn create(&mut self, owner: String) -> Box<Self::Object> { let product = self.create_product(owner); self.register_product(&product); product }
fn create_product(&self, owner: String) -> Box<Self::Object>; fn register_product(&mut self, product: &Box<Self::Object>); }

struct IDCardFactory { owners: Vec<String>, }

impl IDCardFactory { fn new() -> IDCardFactory { IDCardFactory { owners: Vec::new(), } } }

impl Factory for IDCardFactory { type Object = IDCard; fn create_product(&self, owner: String) -> Box<Self::Object> { Box::new(IDCard::new(owner)) }
fn register_product(&mut self, product: &Box<Self::Object>) { self.owners.push(product.get_owner()); } }
fn main() { let mut factory = IDCardFactory::new(); let card1 = factory.create("結城浩".to_string()); let card2 = factory.create("とむら".to_string()); let card3 = factory.create("佐藤花子".to_string()); card1.use_product(); card2.use_product(); card3.use_product(); }

Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions

Subscribe to See Videos

Subscribe to my Youtube channel for new videos : Subscribe Now