Prototype Design Pattern in Modern C++ – DZone Web Dev | xxxPrototype Design Pattern in Modern C++ – DZone Web Dev – xxx
菜单

Prototype Design Pattern in Modern C++ – DZone Web Dev

六月 12, 2020 - MorningStar

Over a million developers have joined DZone.

  • Prototype Design Pattern in Modern C++ - DZone Web Dev

    {{node.title}}

    {{node.type}} · {{ node.urlSource.name }} by

    Download {{node.downloads}}

  • {{totalResults}} search results

{{announcement.body}}

{{announcement.title}}

Let’s be friends:

= 1024)” dc-slot=”ads.sl1.slot(articles[0], 0)” tags=”ads.sl1.tags(articles[0], 0)” size=”ads.sl1.size(articles[0], 0)” style=”border:0;”>
1 && !articles[0].partner.isSponsoringArticle && (width >= 1024)” dc-slot=”ads.sb2.slot(articles[0], 0)” tags=”ads.sb2.tags(articles[0], 0)” size=”ads.sb2.size(articles[0], 0)” >

Prototype Design Pattern in Modern C++

DZone ‘s Guide to

Prototype Design Pattern in Modern C++

Prototype Design Pattern helps in the prototyping (creating/copying cheaply) an object using separate methods or polymorphic classes.

Jul. 21, 20 · Web Dev Zone ·

Free Resource

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:

  1.  Factory
  2.  Builder
  3.  Prototype
  4.  Singleton

The code snippets you see throughout this series of articles are simplified. So, you’ll often see me not using keywords like override, final, 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.

Note:

  • 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.

Intent

To create a new object cheaply with the help of an already constructed or pre-initialized stored object.

Prototype Design Pattern in Modern C++ - DZone Web Dev

  • 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.

Motivation

C++

xxxxxxxxxx
1

21

 

1

struct Office {

2

    string         m_street;

3

    string         m_city;

4

    int32_t         m_cubical;

5

6

    Office(string s, string c, int32_t n):m_street(s), m_city(c), m_cubical(n){}

7

};

8

9

struct Employee {

10

struct Office {

0

11

struct Office {

1

12

struct Office {

2

13

struct Office {

3

14

struct Office {

4

15

struct Office {

5

16

struct Office {

6

17

struct Office {

7

18

struct Office {

8

19

struct Office {

9

20

    string         m_street;

0

21

    string         m_street;

1

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 :

C++

    string         m_street;

2

1

16

 

1

    string         m_street;

3

2

    string         m_street;

4

3

    string         m_street;

5

4

    string         m_street;

6

5

    string         m_street;

7

6

    string         m_street;

8

7

    string         m_street;

9

8

    string         m_city;

0

9

    string         m_city;

1

10

    string         m_city;

2

11

    string         m_city;

3

12

    string         m_city;

4

13

    string         m_city;

5

14

    string         m_city;

6

15

    string         m_city;

7

16

    string         m_city;

8

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.
 

A standard way to implement this is by implementing the copy constructor.

Prototype Factory

In the previous example of the Prototype Design Pattern, we basically had a global object for office addresses and used their address for creating prototypes.
 

Now, this isn’t particularly convenient to the consumers of your API because you might want to give them a prototype to work with. And you should explicit enough in terms of letting people know there is the only a unified way by which they create instances from a prototype and so that they cannot make individual instances by themselves.
 
In this case, what you would build is off-course is a Prototype Factory:

C++

    string         m_city;

9

1

64

 

1

    int32_t         m_cubical;

0

2

    int32_t         m_cubical;

1

3

    int32_t         m_cubical;

2

4

    int32_t         m_cubical;

3

5

    int32_t         m_cubical;

4

6

    int32_t         m_cubical;

5

7

    int32_t         m_cubical;

6

8

    int32_t         m_cubical;

7

9

    int32_t         m_cubical;

8

10

    int32_t         m_cubical;

9

11

0

12

1

13

2

14

3

15

4

16

5

17

6

18

7

19

8

20

9

21

    Office(string s, string c, int32_t n):m_street(s), m_city(c), m_cubical(n){}

0

22

    Office(string s, string c, int32_t n):m_street(s), m_city(c), m_cubical(n){}

1

23

    Office(string s, string c, int32_t n):m_street(s), m_city(c), m_cubical(n){}

2

24

    Office(string s, string c, int32_t n):m_street(s), m_city(c), m_cubical(n){}

3

25

    Office(string s, string c, int32_t n):m_street(s), m_city(c), m_cubical(n){}

4

26

    Office(string s, string c, int32_t n):m_street(s), m_city(c), m_cubical(n){}

5

27

    Office(string s, string c, int32_t n):m_street(s), m_city(c), m_cubical(n){}

6

28

    Office(string s, string c, int32_t n):m_street(s), m_city(c), m_cubical(n){}

7

29

    Office(string s, string c, int32_t n):m_street(s), m_city(c), m_cubical(n){}

8

30

    Office(string s, string c, int32_t n):m_street(s), m_city(c), m_cubical(n){}

9

31

};

0

32

};

1

33

};

2

34

};

3

35

};

4

36

};

5

37

};

6

38

};

7

39

};

8

40

};

9

41

0

42

1

43

2

44

3

45

4

46

5

47

6

48

7

49

8

50

9

51

struct Employee {

0

52

struct Employee {

1

53

struct Employee {

2

54

struct Employee {

3

55

struct Employee {

4

56

struct Employee {

5

57

struct Employee {

6

58

struct Employee {

7

59

struct Employee {

8

60

struct Employee {

9

61

struct Office {

00

62

struct Office {

01

63

struct Office {

02

64

struct Office {

03

The subtle thing to note here is the private constructor of Employee and friend EmployeeFactory. This is how we enforce the client/API-user to create an instance of Employee only through EmployeeFactory .

Leveraging Prototype Design Pattern to Implement Virtual Copy Constructor

In 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.

Problem

C++ 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.
 

Moreover, you can’t create an object unless you know its static type because the compiler must know the amount of space it needs to allocate. For the same reason, copy of an object also requires its type to known at compile-time.
 
Consider the following example as problem statement:

C++

struct Office {

04

1

17

 

1

struct Office {

05

2

struct Office {

06

3

struct Office {

07

4

struct Office {

08

5

struct Office {

09

6

struct Office {

10

7

struct Office {

11

8

struct Office {

12

9

struct Office {

13

10

struct Office {

14

11

struct Office {

15

12

struct Office {

16

13

struct Office {

17

14

struct Office {

18

15

struct Office {

19

16

struct Office {

20

17

struct Office {

21

Just don’t think of dynamic_cast<>, it’s a code smell.

Solution

The 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.
 

The following code not only implements virtual copy constructor (i.e. clone()) but also implement virtual constructor(i.e. create()).

C++

 

struct Office {

22

1

21

 

1

struct Office {

23

2

struct Office {

24

3

struct Office {

25

4

struct Office {

26

5

struct Office {

27

6

struct Office {

28

7

struct Office {

29

8

struct Office {

30

9

struct Office {

31

10

struct Office {

32

11

struct Office {

33

12

struct Office {

34

13

struct Office {

35

14

struct Office {

36

15

struct Office {

37

16

struct Office {

38

17

struct Office {

39

18

struct Office {

40

19

struct Office {

41

20

struct Office {

42

21

struct Office {

43

Benefits of Prototype Design Pattern

  1.  Prototypes are useful when the object instantiation is expensive, thus avoid expensive "creation from scratch", and support cheap cloning of a pre-initialized prototype.
  2.  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.
  3.  You can simplify the system by producing complex objects more conveniently.
  4.  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.

Like This Article? Read More From DZone

Topics:
c++, cpp, design pattens

Published at DZone with permission of Vishal Chovatiya . See the original article here.

Opinions expressed by DZone contributors are their own.

Web Dev Partner Resources

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.linkDescription }}

{{ parent.urlSource.name }}

by

CORE

· {{ parent.articleDate | date:’MMM. dd, yyyy’ }} {{ parent.linkDate | date:’MMM. dd, yyyy’ }}



Notice: Undefined variable: canUpdate in /var/www/html/wordpress/wp-content/plugins/wp-autopost-pro/wp-autopost-function.php on line 51