Created
June 28, 2022 21:29
-
-
Save atakde/eb6d832e499cb15eb68685732d64a2fd to your computer and use it in GitHub Desktop.
Abstract Factory Design Pattern PHP Example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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