Skip to content

Instantly share code, notes, and snippets.

@aybarsyalcin
Last active May 13, 2017 20:01
Show Gist options
  • Save aybarsyalcin/564a3606891d113981b5 to your computer and use it in GitHub Desktop.
Save aybarsyalcin/564a3606891d113981b5 to your computer and use it in GitHub Desktop.
Factory Pattern for Swift
import Foundation
class Circle : Shape{
func draw() {
print("Inside \(self.dynamicType)::draw() method.")
}
}
import Foundation
class Rectangle: Shape {
func draw() {
print("Inside \(self.dynamicType)::draw() method.")
}
}
import Foundation
protocol Shape{
func draw()
}
import Foundation
class Square: Shape{
func draw() {
print("Inside \(self.dynamicType)::draw() method.")
}
}
import Foundation
class ShapeFactory : NSObject{
func getShape(shapeType: String) ->Shape? {
if (shapeType == ""){
return nil
}
else if (shapeType == "Circle"){
return Circle()
}
else if (shapeType == "Rectangle"){
return Rectangle()
}
else if (shapeType == "Square"){
return Square()
}
return nil
}
}
let shapeFactory : ShapeFactory = ShapeFactory()
let shape1 = shapeFactory.getShape("Circle")
shape1?.draw()
let shape2 = shapeFactory.getShape("Rectangle")
shape2?.draw()
let shape3 = shapeFactory.getShape("Square")
shape3?.draw()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment