Evgenii Legotckoi
Evgenii Legotckoi25 вересня 2018 р. 16:16

Приклад - Фабричний метод в PHP

Зміст

У шаблоні Factory Method, фабричний метод визначає, які функції мають бути доступні не абстрактній конкретній фабриці. Ці функції мають можливість створювати об'єкти, які є розширеннями певного класу. Який саме підклас створюється, залежить від значення параметра, переданого функції.

У цьому прикладі ми маємо фабричний метод AbstractFactoryMethod , який реалізує функцію makePHPBook($param)

Конкретний клас OReillyFactoryMethod factory розширює клас AbstractFactoryMethod і може створити правильне розширення класу AbstractPHPBook для заданого значення $param.


<?php

abstract class AbstractFactoryMethod {
    abstract function makePHPBook($param);
}

class OReillyFactoryMethod extends AbstractFactoryMethod {
    private $context = "OReilly";  
    function makePHPBook($param) {
    $book = NULL;   
        switch ($param) {
            case "us":
                $book = new OReillyPHPBook;
            break;
            case "other":
                $book = new SamsPHPBook;
            break;
            default:
                $book = new OReillyPHPBook;
            break;        
        }     
    return $book;
    }
}

class SamsFactoryMethod extends AbstractFactoryMethod {
    private $context = "Sams";
    function makePHPBook($param) {
        $book = NULL;
        switch ($param) {
            case "us":
                $book = new SamsPHPBook;
            break;      
            case "other":
                $book = new OReillyPHPBook;
            break;
            case "otherother":
                $book = new VisualQuickstartPHPBook;
            break;
            default:
                $book = new SamsPHPBook;
            break;    
        }     
        return $book;
    }
}

abstract class AbstractBook {
    abstract function getAuthor();
    abstract function getTitle();
}

abstract class AbstractPHPBook {
    private $subject = "PHP";
}

class OReillyPHPBook extends AbstractPHPBook {
    private $author;
    private $title;
    private static $oddOrEven = 'odd';
    function __construct() {
        //alternate between 2 books
        if ('odd' == self::$oddOrEven) {
            $this->author = 'Rasmus Lerdorf and Kevin Tatroe';
            $this->title  = 'Programming PHP';
            self::$oddOrEven = 'even';
        } else {
            $this->author = 'David Sklar and Adam Trachtenberg';
            $this->title  = 'PHP Cookbook'; 
            self::$oddOrEven = 'odd';
        }  
    }
    function getAuthor() {return $this->author;}
    function getTitle() {return $this->title;}
}

class SamsPHPBook extends AbstractPHPBook {
    private $author;
    private $title;
    function __construct() {
        //alternate randomly between 2 books
        mt_srand((double)microtime()*10000000);
        $rand_num = mt_rand(0,1);      

        if (1 > $rand_num) {
            $this->author = 'George Schlossnagle';
            $this->title  = 'Advanced PHP Programming';
        } else {
            $this->author = 'Christian Wenz';
            $this->title  = 'PHP Phrasebook'; 
        }  
    }
    function getAuthor() {return $this->author;}
    function getTitle() {return $this->title;}
}

class VisualQuickstartPHPBook extends AbstractPHPBook {
    private $author;
    private $title;
    function __construct() {
      $this->author = 'Larry Ullman';
      $this->title  = 'PHP for the World Wide Web';
    }
    function getAuthor() {return $this->author;}
    function getTitle() {return $this->title;}
}

  writeln('START TESTING FACTORY METHOD PATTERN');
  writeln('');

  writeln('testing OReillyFactoryMethod');
  $factoryMethodInstance = new OReillyFactoryMethod;
  testFactoryMethod($factoryMethodInstance);
  writeln('');

  writeln('testing SamsFactoryMethod');
  $factoryMethodInstance = new SamsFactoryMethod;
  testFactoryMethod($factoryMethodInstance);
  writeln('');

  writeln('END TESTING FACTORY METHOD PATTERN');
  writeln('');

  function testFactoryMethod($factoryMethodInstance) {
    $phpUs = $factoryMethodInstance->makePHPBook("us");
    writeln('us php Author: '.$phpUs->getAuthor());
    writeln('us php Title: '.$phpUs->getTitle());

    $phpUs = $factoryMethodInstance->makePHPBook("other");
    writeln('other php Author: '.$phpUs->getAuthor());
    writeln('other php Title: '.$phpUs->getTitle());

    $phpUs = $factoryMethodInstance->makePHPBook("otherother");
    writeln('otherother php Author: '.$phpUs->getAuthor());
    writeln('otherother php Title: '.$phpUs->getTitle());
  }

  function writeln($line_in) {
    echo $line_in."<br/>";
  }
?>

Висновок

START TESTING FACTORY METHOD PATTERN

testing OReillyFactoryMethod
us php Author: Rasmus Lerdorf and Kevin Tatroe
us php Title: Programming PHP
other php Author: George Schlossnagle
other php Title: Advanced PHP Programming
otherother php Author: David Sklar and Adam Trachtenberg
otherother php Title: PHP Cookbook


testing SamsFactoryMethod
us php Author: Christian Wenz
us php Title: PHP Phrasebook
other php Author: Rasmus Lerdorf and Kevin Tatroe
other php Title: Programming PHP
otherother php Author: Larry Ullman
otherother php Title: PHP for the World Wide Web


END TESTING FACTORY METHOD PATTERN
Рекомендуємо хостинг TIMEWEB
Рекомендуємо хостинг TIMEWEB
Стабільний хостинг, на якому розміщується соціальна мережа EVILEG. Для проектів на Django радимо VDS хостинг.

Вам це подобається? Поділіться в соціальних мережах!

Коментарі

Only authorized users can post comments.
Please, Log in or Sign up
Ua

Qt - Тест 001. Сигналы и слоты

  • Результат:84бали,
  • Рейтинг балів4
Ua

Qt - Тест 001. Сигналы и слоты

  • Результат:42бали,
  • Рейтинг балів-8
ОК

Qt - Тест 001. Сигналы и слоты

  • Результат:47бали,
  • Рейтинг балів-6
Останні коментарі
ИМ
Игорь Максимов22 листопада 2024 р. 21:51
Django - Підручник 017. Налаштуйте сторінку входу до Django Добрый вечер Евгений! Я сделал себе авторизацию аналогичную вашей, все работает, кроме возврата к предидущей странице. Редеректит всегда на главную, хотя в логах сервера вижу запросы на правильн…
Evgenii Legotckoi
Evgenii Legotckoi31 жовтня 2024 р. 23:37
Django - Урок 064. Як написати розширення для Python Markdown Добрый день. Да, можно. Либо через такие же плагины, либо с постобработкой через python библиотеку Beautiful Soup
A
ALO1ZE19 жовтня 2024 р. 17:19
Читалка файлів fb3 на Qt Creator Подскажите как это запустить? Я не шарю в программировании и кодинге. Скачал и установаил Qt, но куча ошибок выдается и не запустить. А очень надо fb3 переконвертировать в html
ИМ
Игорь Максимов05 жовтня 2024 р. 16:51
Django - Урок 064. Як написати розширення для Python Markdown Приветствую Евгений! У меня вопрос. Можно ли вставлять свои классы в разметку редактора markdown? Допустим имея стандартную разметку: <ul> <li></li> <li></l…
d
dblas505 липня 2024 р. 20:02
QML - Урок 016. База даних SQLite та робота з нею в QML Qt Здравствуйте, возникает такая проблема (я новичок): ApplicationWindow неизвестный элемент. (М300) для TextField и Button аналогично. Могу предположить, что из-за более новой верси…
Тепер обговоріть на форумі
AH
Abdul Hadi13 лютого 2025 р. 15:21
Are you Looking for best painter services in Qatar? Looking for top painter Services in Qatar? Get high-quality, affordable, and professional painting for homes & offices. Contact expert painters today!
d
dubaicushions13 лютого 2025 р. 15:17
Are Looking for custom swing cushions in Dubai for home decor? Looking for Custom Swing Cushions in Dubai? Get high-quality, weather-resistant, and stylish cushions for your outdoor swing. Order now for comfort & elegance!
d
dubaicustomizedsofa13 лютого 2025 р. 15:11
Are you Looking for a custom sofa in Dubai? Looking for a Custom Sofa in Dubai ? Get high-quality, stylish, and tailor-made sofas to match your space. Order now for comfort, luxury, and perfect design!
b
blinds1211 лютого 2025 р. 16:08
Why Bamboo Blinds Are the Perfect Choice for Your Home When it comes to enhancing the aesthetics and functionality of your living space, choosing the right window treatment is crucial. Bamboo blinds have emerged as a popular choice for homeowners wh…
i
imperial313011 лютого 2025 р. 15:40
How to Select the Right Carpet for Your Bedroom Aesthetic Choosing the perfect carpet for your bedroom involves more than just picking a color or pattern you like. Carpets can transform the ambiance of your space, adding warmth, comfort, and style. How…

Слідкуйте за нами в соціальних мережах