Structural Design Patterns in Swift
Adapter: To unify the interfaces of incompatible classes that already exists
Bridge: It decouples abstraction from its implementation, so that we can change them independently. It reduces the impact of changes
Decorator: Used to add new responsibilities to objects without modifying the underlying classes
Composite pattern: Describes how to combine objects so that each of them can be either simple or composite object.
Facade: Allows us to expose functionality of entire sub system via single class
Fly weight pattern: Used to effectively sharing no. of instances of a class by reducing number of object instances at runtime.
Proxy pattern: Proxy objects acts as a surrogate for more complex objects that me expensive for create or use.
Eg., Two classes A and B are implementing a protocol P, so we use polymorphism to call the methods of A and B classes. Now when a new class C does not implement the protocol P and we need to use the class C along with A and B, we couldn’t do it as the interface is different. In order to add the new method/interface to C (similar to A and B) we need Adapter Pattern
Adapter Pattern can be used in two ways
- Creating new adapter class:
Creating class D which adopts method protocol P and insod
protocol P {
func shareMessage(msg: String)
}
class D: P {
func shareMessage(msg: String) {
someObjectWithDifferentInterface.differentMethod(message: msg)
}
} - Extending existing class to add new functionality:
extension C: P {
func shareMessage(msg: String) {
someObjectWithDifferentInterface.differentMethod(message: msg)
}
}
Comments
Post a Comment