Skip to content

Instantly share code, notes, and snippets.

@iamcrypticcoder
Last active March 28, 2018 18:56
Show Gist options
  • Save iamcrypticcoder/0933f000c87811c312b7969ba5886517 to your computer and use it in GitHub Desktop.
Save iamcrypticcoder/0933f000c87811c312b7969ba5886517 to your computer and use it in GitHub Desktop.
protocol AbstractGUIFactory {
func createButton() -> Button
func createWindow() -> Window
}
protocol Button {
func setTitle(_ title: String) -> Void
func show() -> Void
}
protocol Window {
func setTitle(_ title: String) -> Void
func show() -> Void
}
class WinFactory : AbstractGUIFactory {
func createButton() -> Button {
return WinButton()
}
func createWindow() -> Window {
return WinWindow()
}
}
class OSXFactory : AbstractGUIFactory {
func createButton() -> Button {
return OSXButton()
}
func createWindow() -> Window {
return OSXWindow()
}
}
class WinButton: Button {
var title: String?
func setTitle(_ title: String) -> Void {
self.title = title
}
func show() -> Void {
print("Showing Windows style button [Title: \(self.title!)]")
}
}
class WinWindow : Window {
var title: String?
func setTitle(_ title: String) -> Void {
self.title = title
}
func show() -> Void {
print("Showing Windows style window [Title: \(self.title!)]")
}
}
class OSXButton : Button {
var title: String?
func setTitle(_ title: String) -> Void {
self.title = title
}
func show() -> Void {
print("Showing OSX style button [Title: \(self.title!)]")
}
}
class OSXWindow : Window {
var title: String?
func setTitle(_ title: String) -> Void {
self.title = title
}
func show() -> Void {
print("Showing OSX style window [Title: \(self.title!)]")
}
}
class GUIBuilder {
private var platform: String
private var guiFactory: AbstractGUIFactory?
init(platform: String) {
self.platform = platform
}
func initGuiFactory() -> Void {
if nil != guiFactory { return }
if platform == "Windows" { guiFactory = WinFactory() }
else { guiFactory = OSXFactory() }
}
func buildButton() -> Button {
initGuiFactory()
return guiFactory!.createButton()
}
func buildWindow() -> Window {
initGuiFactory()
return guiFactory!.createWindow()
}
}
import Foundation
let guiBuilder: GUIBuilder = GUIBuilder(platform: "Windows")
let window: Window = guiBuilder.buildWindow()
window.setTitle("Mahbub")
window.show()
let button: Button = guiBuilder.buildButton()
button.setTitle("Connect")
button.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment