Design pattern in Golang — Prototype
In a real-life scenario, a complex object (e.g. Car, Phone) is not created from scratch. We use the existing design and modify it.
The prototype pattern follows the same principle.
An existing (partially or fully completed) design is a prototype.
To implement the Prototype pattern we need to know Deep Copying.
What is Deep Copying?
It's a fancy term to copy data from one object to another.
Why is it fancy?
Because there is a catch!
If an object has a property that is a reference (pointer) to another object. We cannot just perform a direct copy.
Let's take a look at this example.
- Since
Name
is a passed as a value type, it is copied successfully. - The address is a reference type so even when we create a new
employee2
we still are referencing the sameAddress
instance ofemployee1
. (see the output)
We can achieve Deep Copying in 2 ways, As we go through these 2 approaches, you would realise that deep copying through serialization (approach 2) makes more sense (Sorry for the spoilers)
Approach 1 — Copy function
The code is self-explanatory, we created a DeepCopy()
( 15–20
) as part of Address
and performed a deep copy on Address
.
If we run this code, we see correct results.
Approach 2 — Copy through serialization
The downside of approach 1 is, for every new reference type property, we need to create a Copy
function. Imagine extending Employee
with a new reference type property called Contract
!
We need to write a new Copy()
for Contract
so that the contract object can be deep copied.
Now, you can already imagine why Copy through serialization is better.
When you serialize an object and deserialize it into another object, all the new references are initialized properly without the developer writing too much code.
Let us see this example.
Imagine a scenario where you need to create Person
objects working in the same company. The Person
struct has 2 reference type properties WorkAddress
and HomeAddress
. Instead of creating 2 clone()
functions (like approach 1), we create a DeepCopy()
through serialization, that can clone one object into another.
So, in the code above, line 27-34
we used binary serialization to encode an object and create a copy/clone (line55
).
Note: It doesn’t matter what type of serialization you are using to apply this pattern.
In conclusion, we learned that the Prototype Pattern is achieved with deep copying.
The approaches discussed here are not written in stone. Let me know if you have a better approach to implement deep copying!
A good software developer doesn’t try to fit his/her code into a specific design pattern. He/She adheres to SOLID principles.