在以前的一篇关于
适配器(Adapter)模式.NET的文字中,我提到了桥接模式,现在我把它写出来。
桥接模式(Bridge)的为了使开发者完全抽象实现之间的模型,使用多重继承的方式解耦。这就强调了需要出现的三个标志:
1:主操作纯虚类,主要定义实现的方法以及构造时(此处可以灵活)的使用的虚类对象。
2:实现中使用的对象。
3:桥接以上两者,然后按照纯虚方法调用。
以下一个Demo:
using System;
abstract class AbsAnimal{
public AbsPlace Place;
public AbsAnimal(AbsPlace ap){
this.Place=ap;
}
public abstract void Shout();
};
abstract class AbsPlace{
public abstract string GetName();
};
class Shanghai:AbsPlace{
public override string GetName(){
return "In Shanghai,Big City";
}
};
class XuHui:AbsPlace{
public override string GetName(){
return "In XuHui,a district";
}
};
class Cat:AbsAnimal{
public Cat(AbsPlace ap):base(ap){}
public override void Shout(){
Console.WriteLine("Look,A Cat want a Gf");
}
};
class Dog:AbsAnimal{
public Dog(AbsPlace ap):base(ap){}
public override void Shout(){
Console.WriteLine("Wang Wang,A Dog left a Gf");
}
};
public class MainTest{
static void Main(string[] args){
AbsAnimal anm = new Cat(new Shanghai());
Console.WriteLine(anm.Place.GetName());
anm.Shout();
Console.WriteLine("切换:");
anm=new Dog(new XuHui());
Console.WriteLine(anm.Place.GetName());
anm.Shout();
Console.ReadLine();
}
};
以上的
桥接模式的实现主要有三个关系:AbsAnimal,AbsPlace,主实现,可以看到AbsAnimal完全隐藏了其实现的具体细节,AbsPlace也隐藏了其具体实现的细节。这就是在在两个纬度上的解耦。 如此做法,也是为了程序的可扩展性。
上面的Demo输出:
In Shanghai,Big City
Look,A Cat want a Gf
切换:
In XuHui,a district
Wang Wang,A Dog left a Gf
关于
桥接模式(C# .NET)就先写到这里。
天气:大雨,ccdot发表于2008-7-15 9:02:02,阅读了489次,共有个0回复.