The factory pattern is a design pattern that is used to create objects without specifying the exact class of object that will be created. This allows for flexibility in the creation of objects, as the factory can be configured to create different types of objects based on the needs of the application.
In Rust, the factory pattern can be implemented using traits and generics. This allows for the creation of a factory trait that can be implemented by different types of factories, each of which can create different types of objects.
Here is an example of a factory trait and a simple factory implementation that creates objects of type Person:
|
|
In this example, the Factory trait defines a method create that takes a self reference and returns an object of type T. This trait is implemented by the PersonFactory struct, which takes a name and age as parameters and uses them to create a Person object.
To use the factory, we can create an instance of PersonFactory and call the create method to create a new Person object:
|
|
In this example, the factory variable is an instance of PersonFactory with a name of “John Doe” and an age of 30. When the create method is called on this instance, it creates a new Person object with the given name and age.
This example can be extended to create different types of objects based on the needs of the application. For example, we can create a VehicleFactory that creates Car and Truck objects:
|
|
In this example, the VehicleFactory