Factory method is a creational design pattern which solves the problem of creating product objects without specifying their concrete classes.
The Factory Method defines a method, which should be used for creating objects instead of using a direct constructor call (new operator). Subclasses can override this method to change the class of objects that will be created.
If you can’t figure out the difference between various factory patterns and concepts, then read our Factory Comparison.
This example illustrates how to organize a GUI framework into independent modules using dynamic dispatch:
The gui module defines interfaces for all the components.
It has no external dependencies.
The html_gui module provides HTML implementation of the base GUI.
Depends on gui.
The windows_gui module provides Windows implementation of the base GUI.
Depends on gui.
The app is a client application that can use several implementations of the GUI framework, depending on the current environment or configuration. However, most of the app code doesn’t depend on specific types of GUI elements. All client code works with GUI elements through abstract interfaces defined by the gui module.
The Abstract Factory example demonstrates an even greater separation of a factory interface and its implementations.
gui.rs: Product & Creator
html_gui.rs: Concrete creator
windows_gui.rs: Another concrete creator
init.rs: Initialization code
main.rs: Client code
Output
Maze Game
This example illustrates how to implement the Factory Method pattern using static dispatch (generics).