Prototype Design Pattern in Modern C++
Prototype Design Pattern in Modern C++
Prototype Design Pattern helps in the prototyping (creating/copying cheaply) an object using separate methods or polymorphic classes.
Join the DZone community and get the full member experience.Join For Free
Prototype Design Pattern is a Creational Design Pattern that helps in the prototyping(creating/copying cheaply) of an object using separate methods or polymorphic classes. You can consider the prototype as a template of an object before the actual object is constructed. In this article, we're going to take a look at why we need a Prototype Design Pattern in C++ i.e. motivation, prototype factory and leveraging prototype design pattern to implement virtual copy constructor.
By the way, If you haven't check out my other articles on Creational Design Patterns, then here is the list:
The code snippets you see throughout this series of articles are simplified. So, you'll often see me not using keywords like
public just to make code compact and consumable (most of the time) in a single standard screen size. I also prefer
struct instead of
class just to save a line by not writing "
public:" sometimes and also miss virtual destructor, constructor, copy constructor, prefix
std::, deleting dynamic memory, intentionally. I also consider myself a pragmatic person who wants to convey an idea in the simplest way possible rather than the standard way or using jargon.
- If you stumbled here directly, then I would suggest you go through What is design pattern? first, even if it is trivial. I believe it will encourage you to explore more on this topic.
- All of this code you encounter in this series of articles are compiled using C++20(though I have used Modern C++ features up to C++17 in most cases). So if you don't have access to the latest compiler you can use https://wandbox.org/, which has preinstalled boost library as well.
To create a new object cheaply with the help of an already constructed or pre-initialized stored object.
- The prototype provides flexibility to create complex objects cheaply. The concept is to copy an existing object rather than creating a new instance from scratch, something that may include costly operations.
- The existing object then acts as a prototype, and the newly copied object may change the same properties only if required. This approach saves resources and time, especially when object creation is a heavy process.
- So, essentially, the prototype is quite simply a partially or fully initialized object that you make a copy of. And then you subsequently use for your own benefit with variations.
This is not the right approach, as you have to write the main office address again and again for each employee detail. This is cumbersome and becomes more difficult to work with when you want to create an employee list. Moreover, consider the situation when your main office moves to another address.
Prototype Design Pattern Examples in C++
A more pragmatic approach would be like this :
The above solution is suitable for our use case, but sometimes we want to customize that office address. And when it comes to pointers and references and any sort of indirection, ordinary copying using operator equals quite simply does not work.
Prototype FactoryIn the previous example of the Prototype Design Pattern, we basically had a global object for office addresses and used their address for creating prototypes.
The subtle thing to note here is the private constructor of
friend EmployeeFactory. This is how we enforce the client/API-user to create an instance of
Leveraging Prototype Design Pattern to Implement Virtual Copy ConstructorIn C++, Prototype is also useful to create a copy of an object without knowing its concrete type. Hence, it is also known as Virtual Copy Constructor.
ProblemC++ has the support of polymorphic object destruction using its base class' virtual destructor. Equivalent support for creation and copying of objects is missing as С++ doesn't support virtual constructor and virtual copy constructors.
Just don't think of dynamic_cast<>, it's a code smell.
SolutionThe Virtual Constructor/Copy-Constructor technique allows polymorphic creation and copying of objects in C++ by delegating the act of creation and copying the object to the derived class through the use of virtual methods.
clone()) but also implement virtual constructor(i.e.
Benefits of Prototype Design Pattern
- Prototypes are useful when the object instantiation is expensive, thus avoid expensive "creation from scratch", and support cheap cloning of a pre-initialized prototype.
- The prototype provides the flexibility to create highly dynamic systems by defining new behavior through object composition and specifying values for an object's data members at the time of instantiation unlike defining new classes.
- You can simplify the system by producing complex objects more conveniently.
- Especially in C++, Prototype Design Pattern is helpful in creating copy of an object without even knowing its type.
Summary by FAQs
Q. What's the point of using the Prototype Design Pattern?
- To create an object rapidly based on cloning a pre-configured object.
- Useful to remove a bunch of boilerplate code.
- Handy while working with an object without knowing its type.
- Prototype Design Pattern is an obvious choice while you are working with the Command Design Pattern. For example, in HTTP request most of the time header & footer content remains the same, what changes are data. In such a scenario, you should not create an object from scratch. Rather leverage Prototype Design Pattern.
Q. Is the Prototype Design Pattern Really Just Clone?
It isn't if you combine it with the Factory Design Pattern.
Q. Prototype design pattern to be used when creation is costly, but we do create in the clone.
You must be wondering that in Prototype Factory we show above, we are creating instances in the copy constructor. Isn't that expensive. Yes, it is. But just think about HTTP request, its header consist version, encoding type, content type, server-type, etc. Initially, you need a find out these parameters using respective function calls. But once you got these, these are not going to change until connection closed. So there is no point in doing function calls to extract these params over & over. What cost us here is not parameters but their functions to extract value.
Published at DZone with permission of Vishal Chovatiya . See the original article here.
Opinions expressed by DZone contributors are their own.