C#:
using System;
/** "Implementor" */
interface DrawingAPI {
void DrawCircle(double x, double y, double radius);
}
/** "ConcreteImplementor" 1/2 */
class DrawingAPI1 : DrawingAPI {
public void DrawCircle(double x, double y, double radius)
{
System.Console.WriteLine("API1.circle at {0}:{1} radius {2}\n", x, y, radius);
}
}
/** "ConcreteImplementor" 2/2 */
class DrawingAPI2 : DrawingAPI
{
public void DrawCircle(double x, double y, double radius)
{
System.Console.WriteLine("API2.circle at {0}:{1} radius {2}\n", x, y, radius);
}
}
/** "Abstraction" */
interface Shape {
void Draw(); // low-level
void ResizeByPercentage(double pct); // high-level
}
/** "Refined Abstraction" */
class CircleShape : Shape {
private double x, y, radius;
private DrawingAPI drawingAPI;
public CircleShape(double x, double y, double radius, DrawingAPI drawingAPI) {
this.x = x; this.y = y; this.radius = radius;
this.drawingAPI = drawingAPI;
}
// low-level i.e. Implementation specific
public void Draw() { drawingAPI.DrawCircle(x, y, radius); }
// high-level i.e. Abstraction specific
public void ResizeByPercentage(double pct) { radius *= pct; } }
/** "Client" */
class BridgePattern {
public static void Main(string[] args) {
Shape[] shapes = new Shape[2];
shapes[0] = new CircleShape(1, 2, 3, new DrawingAPI1());
shapes[1] = new CircleShape(5, 7, 11, new DrawingAPI2());
foreach (Shape shape in shapes) {
shape.ResizeByPercentage(2.5);
shape.Draw();
}
}
}
Scheme:
(define (circle-draw-it-one-way x y radius)
(print "du ritar cirkeln här: " x "," y " och den är så stor: " radius))
(define (circle-draw-it-another-way x y radius)
(print "you drew a circle at: " x "," y " with radius: " radius))
(define (circle x y radius api)
(lambda args
(case (car args)
((draw) (api x y radius))
;; again, the following line is a straight port of the C# version, not idiomatic scheme:
((resize-percent!) (set! radius (* 0.01 radius (cadr args)))))))
;; client
(define shapes (list (circle 1 2 3 circle-draw-it-one-way)
(circle 5 7 11 circle-draw-it-another-way)))
(for-each (lambda (c) (c 'resize-percent! 2.5) (c 'draw)) shapes)
The main improvement is not having to define entire classes for a simple drawing wrapper, just the procedure you need.