The prototype pattern is used when the type of objects to create is determined by a prototypical instance, which is cloned to produce new objects. This pattern is used to:
- avoid subclasses of an object creator in the client application..
- avoid the inherent cost of creating a new object in the standard way (e.g., using the 'new' keyword) when it is prohibitively expensive for a given application.
| <?php | |
| Class Book { | |
| private $title = ''; | |
| public function setTitle($title) { | |
| $this->title = $title; | |
| } | |
| public function getTitle() { | |
| return $this->title; | |
| } | |
| public function __clone() {} | |
| } | |
| $newBook = new Book(); | |
| $newBook->setTitle("oops"); | |
| $title = $newBook->getTitle(); | |
| echo $title; | |
| echo "<br>"; | |
| $newBook2 = clone $newBook; | |
| $newBook2->setTitle("designPattern"); | |
| $title = $newBook2->getTitle(); | |
| echo $title; | |
| echo "<br>"; | |
| $newBook3 = $newBook; | |
| $newBook3->setTitle("newTittle"); | |
| echo $newBook->getTitle(); | |
| ?> |
No comments:
Post a Comment