返回首页

Design patterns by Tutorials— The power of OOP (part 3)

Adapter pattern in Swift Swift adapter pattern

Design patterns by Tutorials— The power of OOP (part 3)

Prerequisites — This tutorials series requires an intermediate level of expertise in object-oriented programming. You should have basic knowledge about class, object, constructor, inheritance, value and reference type. An Intermediates will gain knowledge and experts will sharpen his or her knowledge by reading this series from start to finish. Prerequisite—This tutorial series requires intermediate expertise in object-oriented programming. You should have a basic understanding of classes, objects, constructors, inheritance, value and reference types. Intermediate users will gain knowledge, while experts will improve their knowledge by reading this series from cover to cover.

What is an Adapter?

What is an adapter?

An adapter is a physical device that allows one hardware or electronic interface to be adapted to another hardware or electronic interface without loss of functionality. An adapter is a physical device that allows one hardware or electronic interface to be adapted to another hardware or electronic interface without loss of functionality.

Adapters are used when you have one form of input and you want to access something that cannot take your form of input. Adapters are used when you have a form of input and want to access something that cannot take the form of your input.

Now It’s time to understand the adapter pattern by answering below simple questions. Now, understand the adapter pattern by answering the simple questions below.

  1. What is the Adapter pattern in Object-Oriented programming? What is the adapter pattern in object-oriented programming?

  2. What problem does it solve? What problem does it solve?

  3. How can we use it in programming? How do we use it in programming?

What is the Adapter pattern in Object-Oriented programming?

What is the adapter pattern in object-oriented programming?

In the adapter pattern, we define one class that takes the existing type as an input and give us the required type or required functionality/properties to access. In Adapter pattern, we define a class that accepts an existing type as input and gives us the required type or required functionality/properties to access.

What problem does it solve?

What problem does it solve?

It helps to convert existing types of data to another form of data. It helps in converting existing type of data into another form of data.

This is pretty useful when we use code of third party frameworks or library and it accepts restricted types only. This is very useful when we use code from a third-party framework or library and it only accepts restricted types.

How we can use it in programming?

How do we use it in programming?

Let’s understand this with the below example. Let us understand this through the following example.

We have classes like Point, LineSegment and DrawingPad . We have classes Point, LineSegment and DrawingPad.

Remember our old school days of Computer Graphics using C language? Remember the days when we used C language to do computer graphics? That time just to draw a line on the screen, we have to calculate all the points of the line between given two points. To calculate points of line there are multiple basic algorithms available like simple line drawing algorithm, DDA Algorithm, Bresenham’s line algorithm etc. In order to draw a line on the screen, we need to count all the points between two points on this line. In order to calculate the points of a straight line, there are many basic algorithms that can be used, such as simple straight line drawing algorithm, DDA algorithm, Bresenham straight line algorithm, etc. We will keep our example code clean and easy to understand for the adapter pattern without writing this complex algorithms here. For the adapter pattern, we will keep the example code simple and easy to understand without writing such complex algorithms here.

// 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)
        }
    }
}



func main(){
    let drawingPad = DrawingPad()
    
    let point1 = Point(x: 10, y: 10)
    
    drawingPad.draw(point: point1)
}

//call main function to execute code
main()


// AdapterPattern_intro.swift 

In the above example

In the above example

Line 6, class Point represents a single point. Line 6, class Point represents a point.

Line 16, class LineSegment represents a line segment. Line 16, class LineSegment represents a line segment.

Line 29, classDrawingPad represents a canvas for drawing. DrawingPad can draw single or multiple points on a canvas. Line 29, class DrawingPad represents a canvas used for drawing. DrawingPad can draw single or multiple points on the canvas.

We can draw a point in this example but can’t draw a line segment directly on the canvas using a drawing pad instance. Here adapter pattern comes in rescue, thanks to the adapter pattern. We can draw a point in this example, but we cannot draw a line segment directly on the canvas using an artboard instance. Here, the adapter pattern comes into play, thanks to the adapter pattern.

// 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()

//AdapterPattern_simpleSolution.swift

Line45, class LineSegmentToPointAdapter represents an adapter which is the core concept of this article. It takes the existing type LineSegment as an input and gives us an array of points in our case. Line45, class Linesegmenttopadapter represents an adapter, which is the core concept of this article. It takes as input an existing type LineSegment and gives us an array of points in this case.

###Conclusion Conclusion

  1. An adapter is any class that takes the one object as a parameter in the constructor. An adapter is any class that accepts an object as a parameter in its constructor.

  2. An adapter class has properties/methods that we can use as the required type. The adapter class has properties/methods that can be used as the required type.

  3. An adapter can also directly act a required type, that depends on implementation. Adapters can also directly play the required type, depending on the implementation.This is just a simple implementation of the adapter pattern in Object-oriented programming using Swift. But wait, there is something more and advance in this pattern. This is just a simple implementation of the Adapter pattern in object-oriented programming using Swift. But wait, there’s a lot more stuff and progression in this mode.

The adapter design pattern is more powerful with…. The Adapter Design Pattern is even more powerful…

More content coming soon… More coming soon…

Click to view the original text: https://medium.com/flawless-app-stories/adapter-pattern-design-patterns-by-tutorials-the-power-of-oop-part-3-112a956c1101

FAQ

读完之后,下一步看什么

如果还想继续了解,可以从下面几个方向接着读。

Related

继续阅读

这里整理了同分类、同标签或同类问题的文章。