Prototype Pattern of Creational Design Patterns for .Net Core
Problem :
Let’s say we have an application where we receive online orders. In this application, users want to re-create their orders from the past.
In other words, I have listed my previous orders on my orders page, I want to create another one from my previous order with a single button.
public Order Repeat(){ var dbOrder = GetOrder(); Order newOrder = new Order{ Address = dbOrder.Address, Contact = dbOrder.Contact, Id = Guid.NewGuid(), TotalPrice = dbOrder.TotalPrice};return newOrder;}
To do this, I pulled the past order from the database. I created a new order object and set all values to the order class I just created.
I have to keep track of when a new property is added or removed from the order object.
Solution :
In fact although the only changing value of the order received from the database is the “Id” value, we have to set all the values.
We can make a method where we take a column of the object and change only the id value. Here we will find solution with prototype pattern.
We will implement the “ICloneable” interface of the order class we created. So it will have to create the “Clone()” method.
Within the Clone method we will create a shallow copy using the “MemberwiseClone()” method from the .net system class.
The value that makes the order unique is the “Id” value. We can create a new order depending on the user by changing the “Id” value we get from the DB.
Using the Clone() method, I created the “Repeat()” method, where we change only the “Id” value.
I get a copy of the previous order without having to re-set the Contact, Address, TotalPrice values. Here I am assigning a new value with Guid.NewId() .
A new value to be added or removed from the order class no longer affects me.
Repo Url :
Yazının Türkçe Kaynağı İçin :
http://www.sametcinar.com/prototype-pattern-of-creational-design-patterns-for-net-core/