How to realize the factory model in C++
This article mainly explains "how to realize the factory model in C++". The content in the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought. Let's study and learn how to realize the factory model in C++.
The principle of polymorphism is used in the factory mode to decouple the concrete implementation and interface effectively, which accords with the principle of opening and closing and the principle of dependency inversion.
When new features are needed, there is no need to modify the original code.
Abstract class human and abstract class factory are called interfaces, while the actual production process is new through subclasses of factory (such as boyfactory)
A specific human (such as: boy) subclass then returns the pointer completion of a human parent class, as shown below:
The specific code is as follows:
Click (here) to collapse or open
# include
Using namespace std
/ / the new feature of factory mode will not modify the original code to comply with the opening and closing principle.
/ / using polymorphic implementation
/ / Pure virtual interface
Class human
{
Public:
Virtual void getman (void) = 0
Virtual ~ human ()
{
/ / cout