Last active
March 10, 2020 10:32
-
-
Save aainaj/2b206f69d88d477f7a20e64255c9956e to your computer and use it in GitHub Desktop.
Example to show prototype design pattern
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
protocol Cloneable { | |
func copy() -> Any | |
} | |
class Message: Cloneable { | |
var to: String | |
var subject: String | |
init(to: String, subject: String) { | |
self.to = to | |
self.subject = subject | |
} | |
func copy() -> Any { | |
return Message(to: to, subject: subject) | |
} | |
} | |
class DetailedMessage: Message { | |
var from: String | |
init(to: String, subject: String, from:String) { | |
self.from = from | |
super.init(to: to, subject: subject) | |
} | |
override func copy() -> Any { | |
return DetailedMessage(to: to, subject: subject, from: from) | |
} | |
} | |
class MessageLogger { | |
var messages:[Message] = [] | |
func logMessage(_ msg: Message) { | |
guard let messageCopy = msg.copy() as? Message else { return } | |
messages.append(messageCopy) | |
} | |
func processMessages(_ callback: (Message) -> Void) { | |
for msg in messages { | |
callback(msg) | |
} | |
} | |
} | |
var logger = MessageLogger() | |
var message = Message(to: "Joe", subject: "Hello") | |
logger.logMessage(message) | |
message.to = "Bob" | |
message.subject = "Free for dinner?" | |
logger.logMessage(message) | |
logger.logMessage(DetailedMessage(to: "Alice", subject: "Hi!", from: "Joe")) | |
logger.processMessages({msg -> Void in | |
if let detailed = msg as? DetailedMessage { | |
print("Detailed Message - To: \(detailed.to) From: \(detailed.from)" + " Subject: \(detailed.subject)") | |
} else { | |
print("Message - To: \(msg.to) Subject: \(msg.subject)") | |
} | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment