Adapter klasowy Java /** * przykład w języku Java */

/* klasa użytkownika powinna tworzyć obiekty adaptera */ /* przy użyciu referencji tego typu */ interface Stack { void push (T o); T pop (); T top (); }

/* klasa adaptowana */ class DList { public void insert (DNode pos, T o) { ... } public void remove (DNode pos) { ... }

public void insertHead (T o) { ... } public void insertTail (T o) { ... }

public T removeHead () { ... } public T removeTail () { ... }

public T getHead () { ... } public T getTail () { ... } }

/* adaptuj klasę DList opakowując ją w interfejs Stack */ class DListImpStack extends DList implements Stack { public void push (T o) { insertTail (o);

public T pop () { return removeTail ();

public T top () { return getTail ();

Python class Adaptee1: def __init__(self, *args, **kw): pass

def specific_request(self): return 'Adaptee1'

class Adaptee2: def __init__(self, *args, **kw): pass

def specific_request(self): return 'Adaptee2'

class Adapter(Adaptee1, Adaptee2): def __init__(self, *args, **kw): Adaptee1.__init__(self, *args, **kw) Adaptee2.__init__(self, *args, **kw)

def request(self): return Adaptee1.specific_request(self), Adaptee2.specific_request(self)

client = Adapter() print client.request()

Adapter obiektowy Java /** * przykład w języku Java */ class LegacyLine { public void draw(int x1, int y1, int x2, int y2) { System.out.println("line from (" + x1 + ',' + y1 + ") to (" + x2 + ',' + y2 + ')');

class LegacyRectangle { public void draw(int x, int y, int w, int h) { System.out.println("rectangle at (" + x + ',' + y + ") with width " + w + " and height " + h);

interface Shape { void draw(int x1, int y1, int x2, int y2);

class Line implements Shape { private LegacyLine adaptee = new LegacyLine();

public void draw(int x1, int y1, int x2, int y2) { adaptee.draw(x1, y1, x2, y2);

class Rectangle implements Shape { private LegacyRectangle adaptee = new LegacyRectangle();

public void draw(int x1, int y1, int x2, int y2) { adaptee.draw( Math.min(x1, x2), Math.min(y1, y2), Math.abs(x2 - x1), Math.abs(y2 - y1) );

public class AdapterDemo { public static void main(String[] args) { Shape[] shapes = { new Line(), new Rectangle() }; // A begin and end point from a graphical editor int x1 = 10, y1 = 20; int x2 = 30, y2 = 60; for (Shape shape : shapes) shape.draw(x1, y1, x2, y2);

//line from (10,20) to (30,60) //rectangle at (10,20) with width 20 and height 40

Python # Python code sample

class Target: def request(self): pass

class Adaptee: def specific_request(self): return 'Hello Adapter Pattern!'

class Adapter(Target): def __init__(self, adaptee): self.adaptee = adaptee

def request(self): return self.adaptee.specific_request()

client = Adapter(Adaptee()) print client.request()