Bridge
The book told me that this pattern is dedicated to decouple the abstraction from its implemetation so they can vary by themself without affecting each others.
To be honest, I don't know which one I should call as abstraction and which one as implemetation. I call them two structures designed for different functions. They focus on different situations, but they should work together to get the things done.
There are so many ways for us available to composite two objects and to let them work together. A very frequent way is to use the inheritance mechanism.
But the inheritance has drawbacks with less flexible in some situations. The inherited class depends on its father class so much. It is hard to modify, to extend.
We can use another way to improve this situation with the new machenism called as Composition and Aggregation. Which makes a "Has" structure compared with the inheritance mechanism with the "is-a" structure.
With the new one, the different parts can work independently but also can work together.
Software design is so flexible that there is no a hard way to let us know to choose which one. it is full of trade-offs based on our experiences and the special situations.
Sometimes the inheritance is good but sometimes the composition or the aggregation is better.
The Bridge Pattern is the very structure which uses the Composition structure to design the system. If you draw the UML of this pattern, you can find dramatically that the structure is like a very bridge, which bidges the two different parts(the two ones the book called as Abstraction and Implementation) and helps them communicate with each other and cooperates with each other.
A small example here to show this pattern:
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
namespace Bridge
{
public abstract class Implementor
{
public abstract void Operation();
}
public class ConcreteImplementorA : Implementor
{
public override void Operation()
{
Console.WriteLine("Operation A");
}
}
public class ConcreteImplementorB : Implementor
{
public override void Operation()
{
Console.WriteLine("Operation B");
}
}
public class Abstraction
{
protected Implementor implementor;
public void SetImplementor(Implementor implementor)
{
this.implementor = implementor;
}
public virtual void Operation()
{
implementor.Operation();
}
}
public class RefinedAbstraction : Abstraction
{
public override void Operation()
{
implementor.Operation();
}
}
class Client
{
static void Main(string[] args)
{
Abstraction ab = new RefinedAbstraction();
ab.SetImplementor(new ConcreteImplementorA());
ab.Operation();
ab.SetImplementor(new ConcreteImplementorB());
ab.Operation();
}
}
}