问题描述
有没有人在实际应用中使用过桥接模式?如果是这样,你是如何使用它的?是我,还是只是在混合中加入了一点依赖注入的适配器模式?它真的值得拥有自己的模式吗?
推荐答案
在 UI 环境中定义形状时使用了桥接模式的经典示例(请参阅 桥接模式维基百科条目).Bridge 模式是 组合a href="http://en.wikipedia.org/wiki/Template_method_pattern" rel="noreferrer">模板 和 策略 模式.
在桥接模式中,适配器模式的某些方面是一个常见的观点.但是,引用这篇文章:
<块引用>乍一看,桥接模式看起来很像适配器模式,因为一个类用于将一种接口转换为另一种接口.然而,适配器模式的意图是使一个或多个类的接口看起来与特定类的接口相同.桥接模式旨在将类的接口与其实现分开,以便您可以在不更改客户端代码的情况下更改或替换实现.
其他推荐答案
Federico's 和
什么时候:
----Shape--- / \ Rectangle Circle / \ / \ BlueRectangle RedRectangle BlueCircle RedCircle
重构为:
----Shape--- Color / \ / \ Rectangle(Color) Circle(Color) Blue Red
其他推荐答案
桥接模式是旧建议"优先组合而不是继承"的应用.当您必须以相互正交的方式对不同时间进行子类化时,它会变得很方便.假设您必须实现彩色形状的层次结构.您不会将 Shape 与 Rectangle 和 Circle 子类化,然后将 Rectangle 与 RedRectangle、BlueRectangle 和 GreenRectangle 子类化,对于 Circle 也是如此,对吗?您更愿意说每个形状有一个颜色并实现颜色层次结构,这就是桥接模式.好吧,我不会实现"颜色层次结构",但你明白了......
问题描述
Has anyone ever used the Bridge Pattern in a real world application? If so, how did you use it? Is it me, or is it just the Adaptor Pattern with a little dependency injection thrown into the mix? Does it really deserve its own pattern?
推荐答案
A classic example of the Bridge pattern is used in the definition of shapes in an UI environment (see the Bridge pattern Wikipedia entry). The Bridge pattern is a composite of the Template and Strategy patterns.
It is a common view some aspects of the Adapter pattern in the Bridge pattern. However, to quote from this article:
At first sight, the Bridge pattern looks a lot like the Adapter pattern in that a class is used to convert one kind of interface to another. However, the intent of the Adapter pattern is to make one or more classes' interfaces look the same as that of a particular class. The Bridge pattern is designed to separate a class's interface from its implementation so you can vary or replace the implementation without changing the client code.
其他推荐答案
There's a combination of Federico's and John's answers.
When:
----Shape--- / \ Rectangle Circle / \ / \ BlueRectangle RedRectangle BlueCircle RedCircle
Refactor to:
----Shape--- Color / \ / \ Rectangle(Color) Circle(Color) Blue Red
其他推荐答案
The Bridge pattern is an application of the old advice, "prefer composition over inheritance". It becomes handy when you must subclass different times in ways that are orthogonal with one another. Say you must implement a hierarchy of colored shapes. You wouldn't subclass Shape with Rectangle and Circle and then subclass Rectangle with RedRectangle, BlueRectangle and GreenRectangle and the same for Circle, would you? You would prefer to say that each Shape has a Color and to implement a hierarchy of colors, and that is the Bridge Pattern. Well, I wouldn't implement a "hierarchy of colors", but you get the idea...