Thursday 24 November 2016

Composite Pattern In Swift

Today we learn about composite pattern used in swift. Lets start.
The composite pattern describes that a group of objects is to be treated in the same way as a single instance of an object. The intent of a composite is to "compose" objects into tree structures to represent part-whole hierarchies. Implementing the composite pattern lets clients treat individual objects and compositions uniformly.The composite pattern is used to create hierarchical, recursive tree structures of related objects.

When to use :
Composite should be used when clients ignore the difference between compositions of objects and individual objects. If programmers find that they are using multiple objects in the same way, and often have nearly identical code to handle each of them, then composite is a good choice; it is less complex in this situation to treat primitives and composites as homogeneous.

Structure Of Composite Pattern:
Component
  • is the abstraction for all components, including composite ones
  • declares the interface for objects in the composition
  • (optional) defines an interface for accessing a component's parent in the recursive structure, and implements it if that's appropriate
Leaf
  • represents leaf objects in the composition
  • implements all Component methods
Composite
  • represents a composite Component (component having children)
  • implements methods to manipulate children
  • implements all Component methods, generally by delegating them to its children

Example: 

// Component
protocol Shape {
  func draw(fillColor: String )
}
// Leafs
class Square : Shape{
  func draw(fillColor: String) {
    print("Drawing a Square with color \(fillColor)")

  }
}
class Circle: Shape{
  func draw(fillColor: String) {
    print("Drawing a Circle with color \(fillColor)")

  }
}

// Composite
class Table : Shape{
  lazy var shapes = [Shape]()
  init(_ shapes:Shape...) {
    self.shapes = shapes
  }
  func draw(fillColor: String) {
    for shape in self.shapes{
      shape.draw(fillColor: fillColor)
    }
  }
}
var table = Table(Circle(),Square())
table.draw(fillColor: "Red")

Output:

Drawing a Circle with color Red
Drawing a Square with color Red

Conclusion : 
Today we learn about Composite pattern used in Swift.If you have any questions just leave a comment below and I’ll respond as soon as I can.

No comments:

Post a Comment