Skip to content

Instantly share code, notes, and snippets.

@rwsite
Created March 21, 2021 14:58
Show Gist options
  • Save rwsite/f924440b37e2f38f36eff0a56a3acfbb to your computer and use it in GitHub Desktop.
Save rwsite/f924440b37e2f38f36eff0a56a3acfbb to your computer and use it in GitHub Desktop.
Abstract Factory example in PHP
<?php
/* Abstract Factory in PHP */
interface FactoryOS
{
public static function createMenu() : Menu;
public static function createButton() : Button;
}
class FactoryWin implements FactoryOS
{
public static function createMenu() : Menu
{
return new MenuWin();
}
public static function createButton() : Button
{
return new ButtonWin();
}
}
class FactoryLinux implements FactoryOS
{
public static function createMenu() : Menu
{
return new MenuLinux();
}
public static function createButton() : Button
{
return new ButtonLinux();
}
}
interface Button
{
public function getButtonTitle() : string;
}
class ButtonWin implements Button
{
public $title = "Windows Button";
public function getButtonTitle() : string
{
return $this->title;
}
}
class ButtonLinux implements Button
{
public $title = "Linux Button";
public function getButtonTitle() : string
{
return $this->title;
}
}
interface Menu
{
public function getMenuTitle() : string;
}
class MenuWin implements Menu
{
public $title = "Windows Menu";
public function getMenuTitle() : string
{
return $this->title;
}
}
class MenuLinux implements Menu
{
public $title = "Linux Menu";
public function getMenuTitle() : string
{
return $this->title;
}
}
/* ------------------------------------------------------------------------- */
function createGUIInterface(FactoryOS $f)
{
$menu = $f::createMenu();
$button = $f::createButton();
echo $menu->getMenuTitle() . "<br/>";
echo $button->getButtonTitle();
}
createGUIInterface(new FactoryWin);
echo "<br/>---------------------------<br/>";
createGUIInterface(new FactoryLinux);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment