What is the difference between the bridge pattern and the strategy pattern?

后端 未结 14 2157
予麋鹿
予麋鹿 2020-11-30 20:37

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

14条回答
  •  天命终不由人
    2020-11-30 21:14

    1. Strategy Pattern is used for Behavioural decisions, while Bridge Pattern is used for Structural decisions.

    2. 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()
    

提交回复
热议问题