我们在项目开发的时候,尽量将不变的放在基类中,而让变化的部分在继承类中实现。但是在原始代码设计时,尽量先聚合--合成的设计原则,后在考虑用继承的方式(is-a 则考虑用继承方式);这样在后续维护的时候,就减少维护工作量。桥接模式就是这种方式。
什么是桥接模式?将抽象部分与它实现的部分分离,使得他们都可以独立地变化。嘻嘻,有点不好理解,转换一下:实现系统可能有多个角度分类,每一种分类都有可能变化,那么就把这多种角度分离出来让他们独立变化,减少他们之间的耦合性。项目开发中,我们大部分都要求要面向接口编程;实际上就是让变化部分独立出来,并在另外的地方实现对对象实例的引用,这样保证变化部分的修改不会影响接口本身的调用。
代码区域:
//Implementor 抽象类,声明一个实现的方法
abstract class Implementor
{
public abstract void Operation();
}
//ConcreteImplementorA 具体实现的方法
class ConcreteImplementorA:Implementor
{
public override void Operation()
{
Console.WriteLine("具体的实现方法1");
}
}
//ConcreteImplementorB 具体实现的方法
class ConcreteImplementorB:Implementor
{
public override void Operation()
{
Console.WriteLine("具体的实现方法2");
}
}
//Abstraction 抽象
class Abstraction
{
protected Implementor implementor;
public void SetImplementor(Implementor implementor)
{
this.implementor=implementor;
}
public virtual void Operation()
{
implementor.Operation();
}
}
//RefinedAbstraction 类
class RefinedAbstraction:Abstraction
{
public override void Operation()
{
implementor.Operation();
}
}
//客户端代码
static void Main(string[] arg)
{
Abstraction a=new RefinedAbstraction();
a.SetImplementor(new ConcreteImplementorA());
//调用具体的1实现
a.Operation();
a.SetImplementor(new ConcreteImplementorB());
//调用具体的2实现
a.Operation();
} Android系统为什么能够在生产不同的生产手机厂商的兼容,我想应该有这个设计模式的功劳吧。
原文:http://blog.csdn.net/sevenkj/article/details/43759891