Sunday 26 June 2016

Adapter Design Pattern

This pattern involves a single class which is responsible to join functionalities of independent or incompatible classes.
This particular pattern can be used when your code is dependent on some external API, or any other class that is prone to change frequently.
<?php
Class Book {
private $title = '';
private $author = '';
public function __construct($title, $author) {
$this->title = $title;
$this->author = $author;
}
public function getTitle() {
return $this->title;
}
public function getAuthor() {
return $this->author;
}
}
Class ExtendedBook {
private $book;
public function __construct($book){
$this->book = $book;
}
public function getTitleAndAuthor() {
echo "Title is : ".$this->book->getTitle()." and author is : ".$this->book->getAuthor();
}
}
$book = new Book('design patterns', 'vivek');
$extendedBook = new ExtendedBook($book);
$extendedBook->getTitleAndAuthor();
?>
Here you can see that the ExtendedBook class doesnot have to worry about the changes in
the Book class.
A more practical example would be, if we are using any third party api in our project,
and if we directly use their classes and functions everywhere in our code, then there might
be a situation where the third party decide to modify their api classes and functions, so
now ,we have to change our code where ever we have used their classes.
But if we are using adapter pattern and made a class which acts as a bridge between
the third party api and our implementation of their classes, then we have to only
change our code at only one place i.e. in our adapter class.

No comments:

Post a Comment