Member-only story

Prototype design pattern

The Prototype design pattern is used to create new objects by copying an existing object, known as the prototype.
This pattern allows you to produce new instances by duplicating or cloning an existing one.

UML Flow:-

Let's see the problem first

Imagine, we have a SmartPhone class as bellow:

class SmartPhone {
var name: String
var color: String
private var capacity: Int

// Designed Initializer
init(name: String, color: String, capacity: Int) {
self.name = name
self.color = color
self.capacity = capacity
}
}

Lets try to create object

// Lets try to create object
var obj = SmartPhone(name: "iPhone7", color: "Gray", capacity: 16)

var cloneObj = obj

// Lets try to modify this clone object
cloneObj.name
cloneObj.color
cloneObj.capacity

Problem 1: Capacity is private so it not modify

Problem 2: Because of the reference type if we change the name of cloneObj, its changes in the original obj.

Problem 3: In case of modify cloneObj, client should know about all property of the main obj.

Problem 4:

--

--

No responses yet