Skip to content

Instantly share code, notes, and snippets.

@atakde
Created June 28, 2022 21:29
Show Gist options
  • Save atakde/eb6d832e499cb15eb68685732d64a2fd to your computer and use it in GitHub Desktop.
Save atakde/eb6d832e499cb15eb68685732d64a2fd to your computer and use it in GitHub Desktop.
Abstract Factory Design Pattern PHP Example
<?php
interface CarInterface
{
public function getBrand(): string;
public function getPrice(): int;
}
interface MotorcycleInterface
{
public function getBrand(): string;
public function getPrice(): int;
public function getType(): string;
}
class BmwCar implements CarInterface
{
public function getBrand(): string
{
return 'BMW';
}
public function getPrice(): int
{
return 1;
}
}
class AudiCar implements CarInterface
{
public function getBrand(): string
{
return 'Audi';
}
public function getPrice(): int
{
return 2;
}
}
class BmwMotorcycle implements MotorcycleInterface
{
public function getBrand(): string
{
return 'BMW';
}
public function getPrice(): int
{
return 3;
}
public function getType(): string
{
return 'Sport';
}
}
class AudiMotorcycle implements MotorcycleInterface
{
public function getBrand(): string
{
return 'Audi';
}
public function getPrice(): int
{
return 4;
}
public function getType(): string
{
return 'Sport';
}
}
interface AbstractFactoryInterface
{
public function createCar(): CarInterface;
public function createMotorcycle(): MotorcycleInterface;
}
class AudiFactory implements AbstractFactoryInterface
{
public function createCar(): CarInterface
{
return new AudiCar();
}
public function createMotorcycle(): MotorcycleInterface
{
return new AudiMotorcycle();
}
}
class BmwFactory implements AbstractFactoryInterface
{
public function createCar(): CarInterface
{
return new BmwCar();
}
public function createMotorcycle(): MotorcycleInterface
{
return new BmwMotorcycle();
}
}
$bmwFactory = new BmwFactory();
$bmwCar = $bmwFactory->createCar();
$bmwMotorcycle = $bmwFactory->createMotorcycle();
echo $bmwCar->getBrand() . ' ' . $bmwCar->getPrice() . PHP_EOL;
echo $bmwMotorcycle->getBrand() . ' ' . $bmwMotorcycle->getPrice() . ' ' . $bmwMotorcycle->getType() . PHP_EOL;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment