Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hitendradeveloper/8fccda159b6e7f739b04ef32282c45db to your computer and use it in GitHub Desktop.
Save hitendradeveloper/8fccda159b6e7f739b04ef32282c45db to your computer and use it in GitHub Desktop.
Design patterns by Tutorials - The power of OOP (part 3) - Adapter pattern simple solution example - https://medium.com/p/112a956c1101
// Hitendra Solanki
// Adapter design pattern Playground example
import Foundation
class Point {
var x: Int
var y: Int
init(x: Int, y: Int) {
self.x = x
self.y = y
}
}
class LineSegment {
var startPoint: Point
var endPoint: Point
init(startPoint: Point, endPoint: Point) {
self.startPoint = startPoint
self.endPoint = endPoint
}
}
//Mark:- DrawingPad
// This is just to make example more interesting
// We are just printing the point on Console to make it simple
class DrawingPad {
//Draw Single point, main drawing method
func draw(point: Point) {
print(".")
}
//Draw multiple points
func draw(points: [Point]) {
points.forEach { (point) in
self.draw(point: point)
}
}
}
//Mark: LineSegmentToPointAdapter
// This is responsible to generate all points exists on LineSegment
class LineSegmentToPointAdapter {
var lineSegment: LineSegment
init(lineSegment: LineSegment) {
self.lineSegment = lineSegment
}
func points() -> Array<Point> {
//To make things simple, without complex line drawing algorithms,
//This will only work for points like below
//(10,10) to (20,20)
//(34,34) to (89,89)
//(x,y) to (p,q) where y=x and q=p i.e. (x,x) to (p,p) just to make it simple for this demo
var points: Array<Point> = []
let zipXY = zip(
(self.lineSegment.startPoint.x...self.lineSegment.endPoint.x),
(self.lineSegment.startPoint.y...self.lineSegment.endPoint.y)
)
for (x,y) in zipXY {
let newPoint = Point(x: x, y: y)
points.append(newPoint)
}
return points
}
}
func main(){
let drawingPad = DrawingPad()
//Remeber: (x,y) to (p,q) where y=x and q=p => (x,x) to (p,p) for our points logic to work
//create lineSegment
let startPoint = Point(x: 2, y: 2)
let endPoint = Point(x: 10, y: 10)
let lineSegment = LineSegment(startPoint: startPoint, endPoint: endPoint)
//create adapter
let adapter = LineSegmentToPointAdapter(lineSegment: lineSegment)
//get points from adapter to draw
let points = adapter.points()
drawingPad.draw(points: points) //it will draw total 9 dots on console
}
//call main function to execute code
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment