I tried to read many articles on dofactory, wikipedia and many sites. I have no idea on differences between bridge pattern and the strategy pattern.
I know both of t
Strategy Pattern is used for Behavioural decisions, while Bridge Pattern is used for Structural decisions.
Brigde Pattern separats the abstract elements from the implementation details, while Strategy Pattern is concerned making algorithms more interchangeable.
Strategy Pattern in UML
Brigde Pattern in UML
Strategy Pattern in Swift:
protocol PrintStrategy {
func print(_ string: String) -> String
}
class Printer {
let strategy: PrintStrategy
init(strategy: PrintStrategy) {
self.strategy = strategy
}
func print(_ string: String) -> String {
return self.strategy.print(string)
}
}
class UpperCaseStrategy: PrintStrategy {
internal func print(_ string: String) -> String {
return string.uppercased()
}
}
class LowerCaseStrategy: PrintStrategy {
internal func print(_ string: String) -> String {
return string.lowercased()
}
}
var lower = Printer(strategy: LowerCaseStrategy())
lower.print("I love Software Patterns")
var upper = Printer(strategy: UpperCaseStrategy())
upper.print("I love Software Patterns")
Brigde Pattern in Swift:
protocol Appliance {
func run()
}
protocol Switch {
let appliance: Appliance {get set}
func turnOn()
}
class RemoteControl: Switch {
var appliance: Appliance
init(appliance: Appliance) {
self.appliance = appliance
}
internal func turnOn() {
appliance.run()
}
}
class TV: Appliance {
internal func run() {
print("TV is ON")
}
}
class Stereo: Appliance {
internal func run() {
print("Stereo is ON")
}
}
var tvRemote = RemoteControl.init(appliance: TV())
tvRemote.turnOn()
var stereoRemote = RemoteControl.init(appliance: Stereo())
stereoRemote.turnOn()
Strategy:
Intent is ability to swap behavior at runtime
class Context {
IStrategy strategyReference;
void strategicBehaviour() {
strategyReference.behave();
}
}
Bridge
Intent is to completely decouple the Abstraction from the Implementation
interface IAbstraction {
void behaviour1();
.....
}
interface IImplementation {
void behave1();
void behave2();
.....
}
class ConcreteAbstraction1 implements IAbstraction {
IImplementation implmentReference;
ConcreteAbstraction1() {
implmentReference = new ImplementationA() // Some implementation
}
void behaviour1() {
implmentReference.behave1();
}
.............
}
class ConcreteAbstraction2 implements IAbstraction {
IImplementation implmentReference;
ConcreteAbstraction1() {
implmentReference = new ImplementationB() // Some Other implementation
}
void behaviour1() {
implmentReference.behave2();
}
.............
}