Bridge design pattern with JavaScript
By Dmitry Khudorozhkov

This article explains what the Bridge design pattern is, and presents a minimalistic cross-browser vector graphics (SVG + VML) library, written in JavaScript, built with the help of this pattern. 

Foreword

This article assumes you are familiar with object aspects of the JavaScript language. If not, it is recommended that you read the first half of Salvatore Vetro's article.

This article is organized as follows:

Problem

Graphic content is the thing every web developer deals with every single page created. Problems begin when it goes a little further than placing an <IMG> tag. You may wish to build a web-based graphics editor, game, ad banner, interactive teaser, etc.

The first solution that comes to mind is Flash. You can satisfy almost any web graphics need with it, but disadvantages can be prohibitive. They are: need for investments in docs, tools, and programmers; deficient support for in-browser scripting; incompatibility with numerous web media standards, problems with Flash Player security; etc.

XML-based standards are the alternative. They offer perfect web integration (as XML does), are extensible, and do not require downloading large binary archives. The only drawback is that XML is still an emerging technology, so you'll meet numerous incompatibility issues when dealing with XML grammars.

To start with web graphics, we'll need something simple like this:

<script type="text/javascript">

  var vgr = new VectorGraphics(...);

  vgr.MoveTo(100, 100);
  vgr.Rect(100, 100, "#0F0");

  vgr.MoveTo(350, 350);
  vgr.Circle(50, "#F0F");

  ...

</script>

As usual, there is more than one way to do the job. To be exact, the number of ways is the number of browsers, plug-ins, and standards (cross-multiplied with each other...) on the web. To satisfy the needs of all (or, at least, the majority of) your customers, you must pass all these ways... Do you want to meet the multiple-page-browser-and-platform-detection-stuff (with all those switches and ifs so easy to get lost in) once again? I don't.

So, before we move on with rectangles and circles, we'll have to answer two not-so-simple questions:

The answer is:

Bridge pattern

Note: JavaScript is a prototype-based language, and doesn't support many features common to object-oriented languages. Where it makes sense, I'll make notes describing differences and sideways; they are designated as [JavaScript].

Case study: SVG vs. VML

Note: the situation with SVG/VML was explained (in short) earlier; this section provides an in-depth review of a problem and presents the solution to it.

After-word

I'd like to hear from you. Feel free to e-mail me if you have any questions and/or suggestions.

Links

Recommended reading:

Web:

History