Home > Asp.Net, Design Pattern, IT technique > Bridge Pattern(桥模式)

Bridge Pattern(桥模式)

October 12th, 2008 Arale Leave a comment Go to comments

首先要了解一下桥模式, 桥的作用是什么? 连接,桥起的是连接的作用.引用别人的一个例子,写日志. 我想往数据库中写日志,一个是MySQL数据库,另一个是MSSQL数据库.就设计模式桥模式来实现.
首先要做一个桥. 我们做一个抽象类来叫做ImpLog, 有一个抽象的Execute()方法,这个就是桥.然后声明两个类,一个是NImpLog用于往MSSQL中写入数据的,另一个是JImpLog用于往 MySQL中写入数据的. 这两个类就是需要用桥连接起来的类.

namespace BridgePattern
{
    public abstract class ImpLog
    {
         public abstract void Execute(string log);
    }
}
 
namespace BridgePattern
{
     public class JImpLog:ImpLog
     {
        public override void Execute(string log)
        {
          //throw new NotImplementedException();
		  //写入MSSQL
      }
     }
}
 
namespace BridgePattern
{
    public class NImpLog:ImpLog
    {
         public override void Execute(string log)
         {
             //throw new NotImplementedException();
             //写入MySQL
         }
     }
}

由于NImpLog和JImpLog都是继承自ImpLog,因此,根据继承的原理,ImpLog可以接受该被继承对象创建出来的实体.(太别扭了,就是 NImplog和JImplog new出来的对象可以赋值于ImpLog) 桥建好了,我们要使用这坐桥了,怎么样来使用呢?
好吧,为了使用这座桥,我们创建一个叫做Log的类.

namespace BridgePattern
{
    public class Log
    {
	   protected ImpLog implementor; //this is brige....
       public ImpLog Implementor
       {
            set { implementor = value; }
       }
       public virtual void Write(string log)
       {
            implementor.Execute(log);
       }
    }
}

聪明的你一定发现了,Log类里面使用了我们的桥. 是这样的. 并且细心的你也发现了这里我们声明了一个虚方法来执行Execute(),这个虚方法在其子类里面会被重载, 他的子方法我们写好了,就是DatabaseLog类.

namespace BridgePattern
{
     public class DatabaseLog:Log
     {
         public override void Write(string log)
         {
             implementor.Execute(log);
         }
     }
}

看到这里,我们的桥和如何使用已经做好了,要怎么用呢?

     Log dblog = new DatabaseLog();
     dblog.Implementor = new NImpLog();
     dblog.Write("sss");
     dblog.Implementor = new JImpLog();
     dblog.Write("ssss");

看上面的代码,不用我多少什么了吧.

想看专业一点的可以直接去看原文,原文虽然也很浅显,但是也得自己花一点时间消化一下才能理解.
引用地址:
参考的文章


related post