Thank you for your informative Story. I enjoyed reading it. If you dont mind, I'd like to implement/share my sample Prototype pattern code snippet based on your example.
In my version, when I create a user profile, I need to check if it was created before. Following "Service" class is responsible for that task. Unfortunately it takes us three seconds due to slow internet connection in Turkiye...
class Service {
func checkUserProfileExist(byName name:String) -> Bool{
print("Service and/or Db is busy 3 seconds")
Thread.sleep(forTimeInterval: 3)
return false
}
}class UserProfile: NSCopying {
var name: String
var age: Int
init(){ name = ""; age = 0 }
init(name: String, age: Int) {
//fictional business rule
let isProfileExist = Service().checkUserProfileExist(byName: name)
if isProfileExist { fatalError("ERR: User exist") }
self.name = name
self.age = age
}
func copy(with zone: NSZone? = nil) -> Any {
//(1)
//return UserProfile(name: self.name, age: self.age)
//(2)
var userProfile = UserProfile()
userProfile.name = self.name
userProfile.age = self.age
return userProfile
}
}"copy" method creates a template object and makes a shallow-copy, otherwise, if we use overloaded initializer, we need to wait 3 more seconds for each and every new cloned object.
Now, we don't suffer from substantial amount of memory use or heavy computations in order to prepare the object. This is the beautify of prototyping.
// Usage
let originalProfile = UserProfile(name: "John", age: 30)
print("orginal profile name: ", originalProfile.name)
let clonedProfile = originalProfile.copy() as! UserProfile
clonedProfile.name = "Gökhan"
print("cloned profile name: \(clonedProfile.name) (orginal-name: \(originalProfile.name))")Thank you again for your Story.







