桥梁模式和战略模式之间有什么区别?

时间:2022-09-06 13:25:56

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.

我尝试阅读有关dofactory,*和许多网站的许多文章。我不知道桥梁模式和战略模式之间的差异。

I know both of them decouple an abstraction from its implementation and can change implementation at run time.

我知道它们都将抽象与其实现分离,并且可以在运行时更改实现。

But I still don't know in which situation I should use strategy or in which situation I should use bridge.

但我仍然不知道在哪种情况下我应该使用策略或在哪种情况下我应该使用桥接器。

13 个解决方案

#1


Semantics. From wikipedia:

语义。来自*:

The UML class diagram for the Strategy pattern is the same as the diagram for the Bridge pattern. However, these two design patterns aren't the same in their intent. While the Strategy pattern is meant for behavior, the Bridge pattern is meant for structure.

策略模式的UML类图与Bridge模式的图相同。但是,这两种设计模式的意图并不相同。虽然策略模式适用于行为,但Bridge模式适用于结构。

The coupling between the context and the strategies is tighter than the coupling between the abstraction and the implementation in the Bridge pattern.

上下文和策略之间的耦合比Bridge模式中的抽象和实现之间的耦合更紧密。

As I understand it, you're using the strategy pattern when you're abstracting behavior that could be provided from an external source (eg. config could specify to load some plugin assembly), and you're using the bridge pattern when you use the same constructs to make your code a bit neater. The actual code will look very similar - you're just applying the patterns for slightly different reasons.

据我所知,当你抽象出可以从外部源提供的行为时(例如,config可以指定加载一些插件程序集),你正在使用策略模式,并且当你使用时你正在使用桥接模式相同的结构使你的代码更整洁。实际代码看起来非常相似 - 您只是因为略有不同的原因而应用这些模式。

#2


The Bridge pattern is a structural pattern (HOW DO YOU BUILD A SOFTWARE COMPONENT?). The Strategy pattern is a dynamic pattern (HOW DO YOU WANT TO RUN A BEHAVIOUR IN SOFTWARE?).

桥模式是一种结构模式(您如何构建软件组件?)。策略模式是一种动态模式(您希望如何在软件中运行行为?)。

The syntax is similar but the goals are different:

语法类似,但目标不同:

  • Strategy: you have more ways for doing an operation; with strategy, you can choose the algorithm at run-time and you can modify a single Strategy without a lot of side-effects at compile-time;
  • 策略:你有更多的方法来做手术;使用策略,您可以在运行时选择算法,并且您可以在编译时修改单个策略而不会产生很多副作用;

  • Bridge: you can split the hierarchy of interface and class, join it with an abstract reference (see explication)
  • Bridge:您可以拆分接口和类的层次结构,使用抽象引用将其连接起来(请参阅说明)

#3


Strategy:

  • Context tied to the Strategy: The context Class (possibly Abstract but not really an interface! as u wish to encapsulate out a specific behavior and not the entire implementation) would know/contain the strategy interface reference and the implementation to invoke the strategy behavior on it.
  • 与策略绑定的上下文:上下文类(可能是抽象但不是真正的接口!因为您希望封装特定行为而不是整个实现)将知道/包含策略接口引用和实现以调用策略行为它。

  • Intent is ability to swap behavior at runtime

    Intent是在运行时交换行为的能力

    class Context {
    
         IStrategy strategyReference;
    
         void strategicBehaviour() {
    
            strategyReference.behave();
         }
    
    }
    

Bridge

  • Abstraction not tied to the Implementation: The abstraction interface (or abstract class with most of the behavior abstract) would not know/contain the implementation interface reference
  • 抽象不依赖于实现:抽象接口(或抽象类与大多数行为抽象)不会知道/包含实现接口参考

  • 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();
    
          }
    
          .............
    
    }
    

#4


Bridge: ( A structural pattern)

桥:(结构模式)

Bridge pattern decouples abstraction and implementation and allows both to vary independently.

桥接模式将抽象和实现分离,并允许两者独立变化。

Use this pattern when :

使用此模式时:

  1. Abstractions and implementations have not been decided at compile time
  2. 抽象和实现尚未在编译时决定

  3. Abstractions and implementations should be changed independently
  4. 抽象和实现应该独立更改

  5. Changes in implementation of abstraction should not affect caller application
  6. 抽象实现的变化不应影响调用者应用程序

  7. Client should be insulated from implementation details.
  8. 客户应与实施细节隔离。

Strategy: ( Behavioural pattern)

策略:(行为模式)

Strategy patterns enable you to switch between multiple algorithms from a family of algorithms at run time.

策略模式使您可以在运行时从一系列算法中切换多个算法。

Use Strategy pattern when :

使用策略模式时:

  1. Multiple versions of algorithms are required
  2. 需要多个版本的算法

  3. The behaviour of class has to be changed dynamically at run time
  4. 必须在运行时动态更改类的行为

  5. Avoid conditional statements
  6. 避免条件陈述

Related posts:

When do you use the Bridge Pattern? How is it different from Adapter pattern?

你什么时候使用Bridge Pattern?它与适配器模式有何不同?

Real World Example of the Strategy Pattern

真实世界战略模式的例子

#5


I was thinking the same, but recently I had to use bridge and realized that bridge is using strategy and adding abstraction to the context so that you later can make more changes without changing the client. When using Strategy without the abstraction the design is not as flexible and may require changes to the client later. But when using the whole bridge the design becomes even more flexible. Here you can se how going from Strategy to Bridge gives more flexibility. Also we assume that now "visa" and "master" are not only available on cards but on phones and chips also; and if we use bridge it is much easier to add that support.

我的想法是一样的,但最近我不得不使用网桥并意识到网桥正在使用策略并在上下文中添加抽象,以便您以后可以在不更改客户端的情况下进行更多更改。在没有抽象的情况下使用策略时,设计不够灵活,可能需要稍后更改客户端。但是当使用整个桥时,设计变得更加灵活。在这里,您可以了解从策略到桥梁的更多灵活性。此外,我们假设现在“签证”和“主人”不仅可以在卡上使用,也可以在手机和芯片上使用;如果我们使用bridge,则添加该支持要容易得多。

桥梁模式和战略模式之间有什么区别?

#6


Adding to willcodejavaforfood's answer, they can be the same, in implementation. However you use strategy to swap strategies such as sorting strategy, while you use bridge to bridge the implementations of two object's say a database wrapper, and a network adaptor so the client code can use either working against the same API. So the naming actually says it all

添加到willcodejavaforfood的答案,它们可以在实现中相同。但是,您使用策略来交换策略(例如排序策略),而使用桥接来桥接两个对象的实现,例如数据库包装器和网络适配器,以便客户端代码可以使用针对相同API的工作。所以这个命名实际上就说明了一切

#7


From the wiki on Strategy pattern

从战略模式的维基

The UML class diagram for the Strategy pattern is the same as the diagram for the Bridge pattern. However, these two design patterns aren't the same in their intent. While the Strategy pattern is meant for behavior, the Bridge pattern is meant for structure.

策略模式的UML类图与Bridge模式的图相同。但是,这两种设计模式的意图并不相同。虽然策略模式适用于行为,但Bridge模式适用于结构。

The coupling between the context and the strategies is tighter than the coupling between the abstraction and the implementation in the Bridge pattern.

上下文和策略之间的耦合比Bridge模式中的抽象和实现之间的耦合更紧密。

#8


Just to add to what has already been said about the pattern comparison (difference of intent, ...): the Bridge pattern is also intentionally structured to allow the abstraction hierarchy side to vary. In languages like C# this could imply you have an abstraction base that contains virtual methods as a way to allow intended variations that don't cause problems for existing consumers. Other than that the two patterns might appear identical for the most part.

只是添加已经说过的模式比较(意图的差异,......):Bridge模式也是有意构造的,以允许抽象层次结构方面变化。在像C#这样的语言中,这可能意味着您拥有一个包含虚拟方法的抽象基础,作为一种允许不会给现有消费者带来问题的预期变体的方法。除此之外,这两种模式在大多数情况下可能看起来相同。

#9


Strategy pattern is used when you wish to plug algorithm or strategy at run time. As category of pattern also implies that it deals with behaviour of the objects. On the other hand bridge is structural pattern and deals with structural hierarchy of the objects. It decouples the abstraction from implementation by introducing a refined abstraction between them. Refined abstraction can be confused with the run time strategy plugged (In Strategy pattern). Bridge pattern deals with the structural aspects by providing a mechanism to avoid creating n number of classes.

当您希望在运行时插入算法或策略时,使用策略模式。模式类别也意味着它处理对象的行为。另一方面,桥梁是结构模式,处理对象的结构层次。它通过在它们之间引入精细的抽象来将抽象与实现分离。精简抽象可能与插入的运行时策略混淆(在策略模式中)。桥模式通过提供避免创建n个类的机制来处理结构方面。

#10


  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.

    Brigde Pattern将抽象元素与实现细节分开,而Strategy Pattern则关注使算法更具可互换性。

Strategy Pattern in UML

UML中的策略模式

Brigde Pattern in UML

UML中的Brigde模式

Strategy Pattern in Swift:

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:

Swift中的Brigde模式:

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

#11


For strategy pattern only the implementation varies.

对于战略模式,只有实施方式不同。

Suppose, class A is using class B which has multiple implementations available. So in that case B would be abstract with actual implementation provided at runtime. This is strategy pattern

假设,A类使用的是具有多种可用实现的B类。因此,在这种情况下,B将是抽象的,并且在运行时提供实际实现。这是战略模式

Now if A itself is abstract. Both A and B may vary. You would use Bridge pattern.

现在,如果A本身是抽象的。 A和B都可能不同。你会使用Bridge模式。

#12


I think there's a slight difference between them in the context they're being used.

我认为他们在使用环境中存在细微差别。

I use the Bridge pattern to separate orthogonal concepts which they both belong to a bigger one - to let them vary independently. It usually involves multiple abstractions.

我使用Bridge模式来分离它们都属于较大概念的正交概念 - 让它们独立变化。它通常涉及多个抽象。

IMO, the Strategy pattern is simpler or more flat. It serves to OCP for sure but doesn't necessarily to be part of another and bigger concept like the Bridge pattern.

IMO,战略模式更简单或更平坦。它确实适用于OCP,但不一定是另一个更大的概念,如Bridge模式。

#13


Design pattern types

设计模式类型

  • Behavioural: patterns characterise the ways in which classes or objects interact and distribute responsibility
  • 行为:模式表征类或对象交互和分配责任的方式

  • Structural: patterns deal with the composition of classes or objects.
  • 结构:模式处理类或对象的组合。

  • Creational : patterns are concerned about the process of object creation.
  • 创造性:模式关注对象创建的过程。

Bridge (Structural)

Decouple an abstraction from its implementation so that each may vary. independently. 桥梁模式和战略模式之间有什么区别?

将抽象与其实现分离,以便每个抽象都可以变化。独立。

Take a remote. The remote has buttons 1-6. This is the concrete class in the diagram above. Each button will work different depending on if the remote is used for a TV or DVD. The functionality for each button is abstracted from the implementation by the implementer interface.

拿一个遥控器。遥控器有1-6按钮。这是上图中的具体类。每个按钮的工作方式都不同,具体取决于遥控器是用于电视还是DVD。实现者界面从实现中抽象出每个按钮的功能。

This allows us to change how the remote will work for each device.

这允许我们更改遥控器对每个设备的工作方式。

Strategy (Behavioural)

Define a family of algorithms , encapsulate each one and make them interchangeable. 桥梁模式和战略模式之间有什么区别?

定义一系列算法,封装每个算法并使它们可互换。

In strategy, if we were looking at the remote scenario. The "state" is the entire remote which we swap out by changing the context's state reference. The "concreteStateA" (TV remote) "concreteStateB" (DVD Remote).

在策略中,如果我们正在查看远程场景。 “state”是我们通过更改上下文的状态引用而换出的整个遥控器。 “concreteStateA”(电视遥控器)“concreteStateB”(DVD遥控器)。

Additional reading:

#1


Semantics. From wikipedia:

语义。来自*:

The UML class diagram for the Strategy pattern is the same as the diagram for the Bridge pattern. However, these two design patterns aren't the same in their intent. While the Strategy pattern is meant for behavior, the Bridge pattern is meant for structure.

策略模式的UML类图与Bridge模式的图相同。但是,这两种设计模式的意图并不相同。虽然策略模式适用于行为,但Bridge模式适用于结构。

The coupling between the context and the strategies is tighter than the coupling between the abstraction and the implementation in the Bridge pattern.

上下文和策略之间的耦合比Bridge模式中的抽象和实现之间的耦合更紧密。

As I understand it, you're using the strategy pattern when you're abstracting behavior that could be provided from an external source (eg. config could specify to load some plugin assembly), and you're using the bridge pattern when you use the same constructs to make your code a bit neater. The actual code will look very similar - you're just applying the patterns for slightly different reasons.

据我所知,当你抽象出可以从外部源提供的行为时(例如,config可以指定加载一些插件程序集),你正在使用策略模式,并且当你使用时你正在使用桥接模式相同的结构使你的代码更整洁。实际代码看起来非常相似 - 您只是因为略有不同的原因而应用这些模式。

#2


The Bridge pattern is a structural pattern (HOW DO YOU BUILD A SOFTWARE COMPONENT?). The Strategy pattern is a dynamic pattern (HOW DO YOU WANT TO RUN A BEHAVIOUR IN SOFTWARE?).

桥模式是一种结构模式(您如何构建软件组件?)。策略模式是一种动态模式(您希望如何在软件中运行行为?)。

The syntax is similar but the goals are different:

语法类似,但目标不同:

  • Strategy: you have more ways for doing an operation; with strategy, you can choose the algorithm at run-time and you can modify a single Strategy without a lot of side-effects at compile-time;
  • 策略:你有更多的方法来做手术;使用策略,您可以在运行时选择算法,并且您可以在编译时修改单个策略而不会产生很多副作用;

  • Bridge: you can split the hierarchy of interface and class, join it with an abstract reference (see explication)
  • Bridge:您可以拆分接口和类的层次结构,使用抽象引用将其连接起来(请参阅说明)

#3


Strategy:

  • Context tied to the Strategy: The context Class (possibly Abstract but not really an interface! as u wish to encapsulate out a specific behavior and not the entire implementation) would know/contain the strategy interface reference and the implementation to invoke the strategy behavior on it.
  • 与策略绑定的上下文:上下文类(可能是抽象但不是真正的接口!因为您希望封装特定行为而不是整个实现)将知道/包含策略接口引用和实现以调用策略行为它。

  • Intent is ability to swap behavior at runtime

    Intent是在运行时交换行为的能力

    class Context {
    
         IStrategy strategyReference;
    
         void strategicBehaviour() {
    
            strategyReference.behave();
         }
    
    }
    

Bridge

  • Abstraction not tied to the Implementation: The abstraction interface (or abstract class with most of the behavior abstract) would not know/contain the implementation interface reference
  • 抽象不依赖于实现:抽象接口(或抽象类与大多数行为抽象)不会知道/包含实现接口参考

  • 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();
    
          }
    
          .............
    
    }
    

#4


Bridge: ( A structural pattern)

桥:(结构模式)

Bridge pattern decouples abstraction and implementation and allows both to vary independently.

桥接模式将抽象和实现分离,并允许两者独立变化。

Use this pattern when :

使用此模式时:

  1. Abstractions and implementations have not been decided at compile time
  2. 抽象和实现尚未在编译时决定

  3. Abstractions and implementations should be changed independently
  4. 抽象和实现应该独立更改

  5. Changes in implementation of abstraction should not affect caller application
  6. 抽象实现的变化不应影响调用者应用程序

  7. Client should be insulated from implementation details.
  8. 客户应与实施细节隔离。

Strategy: ( Behavioural pattern)

策略:(行为模式)

Strategy patterns enable you to switch between multiple algorithms from a family of algorithms at run time.

策略模式使您可以在运行时从一系列算法中切换多个算法。

Use Strategy pattern when :

使用策略模式时:

  1. Multiple versions of algorithms are required
  2. 需要多个版本的算法

  3. The behaviour of class has to be changed dynamically at run time
  4. 必须在运行时动态更改类的行为

  5. Avoid conditional statements
  6. 避免条件陈述

Related posts:

When do you use the Bridge Pattern? How is it different from Adapter pattern?

你什么时候使用Bridge Pattern?它与适配器模式有何不同?

Real World Example of the Strategy Pattern

真实世界战略模式的例子

#5


I was thinking the same, but recently I had to use bridge and realized that bridge is using strategy and adding abstraction to the context so that you later can make more changes without changing the client. When using Strategy without the abstraction the design is not as flexible and may require changes to the client later. But when using the whole bridge the design becomes even more flexible. Here you can se how going from Strategy to Bridge gives more flexibility. Also we assume that now "visa" and "master" are not only available on cards but on phones and chips also; and if we use bridge it is much easier to add that support.

我的想法是一样的,但最近我不得不使用网桥并意识到网桥正在使用策略并在上下文中添加抽象,以便您以后可以在不更改客户端的情况下进行更多更改。在没有抽象的情况下使用策略时,设计不够灵活,可能需要稍后更改客户端。但是当使用整个桥时,设计变得更加灵活。在这里,您可以了解从策略到桥梁的更多灵活性。此外,我们假设现在“签证”和“主人”不仅可以在卡上使用,也可以在手机和芯片上使用;如果我们使用bridge,则添加该支持要容易得多。

桥梁模式和战略模式之间有什么区别?

#6


Adding to willcodejavaforfood's answer, they can be the same, in implementation. However you use strategy to swap strategies such as sorting strategy, while you use bridge to bridge the implementations of two object's say a database wrapper, and a network adaptor so the client code can use either working against the same API. So the naming actually says it all

添加到willcodejavaforfood的答案,它们可以在实现中相同。但是,您使用策略来交换策略(例如排序策略),而使用桥接来桥接两个对象的实现,例如数据库包装器和网络适配器,以便客户端代码可以使用针对相同API的工作。所以这个命名实际上就说明了一切

#7


From the wiki on Strategy pattern

从战略模式的维基

The UML class diagram for the Strategy pattern is the same as the diagram for the Bridge pattern. However, these two design patterns aren't the same in their intent. While the Strategy pattern is meant for behavior, the Bridge pattern is meant for structure.

策略模式的UML类图与Bridge模式的图相同。但是,这两种设计模式的意图并不相同。虽然策略模式适用于行为,但Bridge模式适用于结构。

The coupling between the context and the strategies is tighter than the coupling between the abstraction and the implementation in the Bridge pattern.

上下文和策略之间的耦合比Bridge模式中的抽象和实现之间的耦合更紧密。

#8


Just to add to what has already been said about the pattern comparison (difference of intent, ...): the Bridge pattern is also intentionally structured to allow the abstraction hierarchy side to vary. In languages like C# this could imply you have an abstraction base that contains virtual methods as a way to allow intended variations that don't cause problems for existing consumers. Other than that the two patterns might appear identical for the most part.

只是添加已经说过的模式比较(意图的差异,......):Bridge模式也是有意构造的,以允许抽象层次结构方面变化。在像C#这样的语言中,这可能意味着您拥有一个包含虚拟方法的抽象基础,作为一种允许不会给现有消费者带来问题的预期变体的方法。除此之外,这两种模式在大多数情况下可能看起来相同。

#9


Strategy pattern is used when you wish to plug algorithm or strategy at run time. As category of pattern also implies that it deals with behaviour of the objects. On the other hand bridge is structural pattern and deals with structural hierarchy of the objects. It decouples the abstraction from implementation by introducing a refined abstraction between them. Refined abstraction can be confused with the run time strategy plugged (In Strategy pattern). Bridge pattern deals with the structural aspects by providing a mechanism to avoid creating n number of classes.

当您希望在运行时插入算法或策略时,使用策略模式。模式类别也意味着它处理对象的行为。另一方面,桥梁是结构模式,处理对象的结构层次。它通过在它们之间引入精细的抽象来将抽象与实现分离。精简抽象可能与插入的运行时策略混淆(在策略模式中)。桥模式通过提供避免创建n个类的机制来处理结构方面。

#10


  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.

    Brigde Pattern将抽象元素与实现细节分开,而Strategy Pattern则关注使算法更具可互换性。

Strategy Pattern in UML

UML中的策略模式

Brigde Pattern in UML

UML中的Brigde模式

Strategy Pattern in Swift:

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:

Swift中的Brigde模式:

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

#11


For strategy pattern only the implementation varies.

对于战略模式,只有实施方式不同。

Suppose, class A is using class B which has multiple implementations available. So in that case B would be abstract with actual implementation provided at runtime. This is strategy pattern

假设,A类使用的是具有多种可用实现的B类。因此,在这种情况下,B将是抽象的,并且在运行时提供实际实现。这是战略模式

Now if A itself is abstract. Both A and B may vary. You would use Bridge pattern.

现在,如果A本身是抽象的。 A和B都可能不同。你会使用Bridge模式。

#12


I think there's a slight difference between them in the context they're being used.

我认为他们在使用环境中存在细微差别。

I use the Bridge pattern to separate orthogonal concepts which they both belong to a bigger one - to let them vary independently. It usually involves multiple abstractions.

我使用Bridge模式来分离它们都属于较大概念的正交概念 - 让它们独立变化。它通常涉及多个抽象。

IMO, the Strategy pattern is simpler or more flat. It serves to OCP for sure but doesn't necessarily to be part of another and bigger concept like the Bridge pattern.

IMO,战略模式更简单或更平坦。它确实适用于OCP,但不一定是另一个更大的概念,如Bridge模式。

#13


Design pattern types

设计模式类型

  • Behavioural: patterns characterise the ways in which classes or objects interact and distribute responsibility
  • 行为:模式表征类或对象交互和分配责任的方式

  • Structural: patterns deal with the composition of classes or objects.
  • 结构:模式处理类或对象的组合。

  • Creational : patterns are concerned about the process of object creation.
  • 创造性:模式关注对象创建的过程。

Bridge (Structural)

Decouple an abstraction from its implementation so that each may vary. independently. 桥梁模式和战略模式之间有什么区别?

将抽象与其实现分离,以便每个抽象都可以变化。独立。

Take a remote. The remote has buttons 1-6. This is the concrete class in the diagram above. Each button will work different depending on if the remote is used for a TV or DVD. The functionality for each button is abstracted from the implementation by the implementer interface.

拿一个遥控器。遥控器有1-6按钮。这是上图中的具体类。每个按钮的工作方式都不同,具体取决于遥控器是用于电视还是DVD。实现者界面从实现中抽象出每个按钮的功能。

This allows us to change how the remote will work for each device.

这允许我们更改遥控器对每个设备的工作方式。

Strategy (Behavioural)

Define a family of algorithms , encapsulate each one and make them interchangeable. 桥梁模式和战略模式之间有什么区别?

定义一系列算法,封装每个算法并使它们可互换。

In strategy, if we were looking at the remote scenario. The "state" is the entire remote which we swap out by changing the context's state reference. The "concreteStateA" (TV remote) "concreteStateB" (DVD Remote).

在策略中,如果我们正在查看远程场景。 “state”是我们通过更改上下文的状态引用而换出的整个遥控器。 “concreteStateA”(电视遥控器)“concreteStateB”(DVD遥控器)。

Additional reading: