Monday, June 8, 2009

Design Pattern: Adapter

The Adapter design pattern is basically a wrapper, that is a class which provides methods to access to another class.
It's commonly used to normalize incompatibile interfaces.
It's similar to Proxy pattern, but it's a little different. Proxy includes an object and controls accesses to it; Adapter provides an interface to the object, usually by inheritance.



class A {
public static function sort(array $ar) { ... }
}

class B {
private $ar;
public function __construct() {}
public function sortElements() { ... };
public function returnArray() { return $ar;}
}

Now we can extend B and provide the same interface as A



class BAdapter extends B {
public static function sort(array $ar) {
$b = new B($ar);
$b->sortElements();
return $b->returnArray();
}
}

now we can use A and B2 in the same way:



print_r( A::sort(array(3,2,4)) );
print_r( BAdapter ::sort(array(3,2,4)) );

No comments:

Post a Comment

 

PHP and tips|PHP