Design Patterns in OOP PHP - Factory Method
Design Patterns in OOP PHP course - Factory Method
- interface car brand have one method
- two brand classes bmwBrand and benzBrand implements car brand
- one interface brand factory
- two classes implements the brand factory and will be responsible for creating new object from the two brand classes bmwBrand and benzBrand
<?php
namespace Creational\FactoryMethod;
interface CarBrandInterface{
public function createBrand();
}
?>
BenzBrand class
<?php
namespace Creational\FactoryMethod;
class BenzBrand implements CarBrandInterface{
public function createBrand(){
return "BenzBrand";
}
}
?>
BmwBrand class
<?php
namespace Creational\FactoryMethod;
class BmwBrand implements CarBrandInterface{
public function createBrand(){
return "BmwBrand";
}
}
?>
BrandFactory class
<?php
namespace Creational\FactoryMethod;
interface BrandFactory{
public function BuildBrand();
}
?>
BmwBrandFactory class
<?php
namespace Creational\FactoryMethod;
class BmwBrandFactory implements BrandFactory{
public function BuildBrand(){
return new BmwBrand();
}
}
?>
<?php
namespace Creational\FactoryMethod;
class BenzBrandFactory implements BrandFactory{
public function BuildBrand(){
return new BenzBrand();
}
}
?>
test cases
<?php
namespace Tests;
use PHPUnit\Framework\TestCase;
use Creational\FactoryMethod\BmwBrandFactory;
use Creational\FactoryMethod\BmwBrand;
use Creational\FactoryMethod\BenzBrandFactory;
use Creational\FactoryMethod\BenzBrand;
class FactoryMethodClassTest extends TestCase{
public function testCanCreateBmWCar(){
$brand=new BmwBrandFactory();
$BmWCarToBe=$brand->BuildBrand();
$this->assertInstanceOf(BmwBrand::Class,$BmWCarToBe);
}
public function testCanCreateBenzCar(){
$brand=new BenzBrandFactory();
$BmWCarToBe=$brand->BuildBrand();
$this->assertInstanceOf(BenzBrand::Class,$BmWCarToBe);
}
}
?>
in terminal run
$ ./vendor/bin/phpunit tests/FactoryMethodClassTest
Runtime: PHP 7.4.28
Configuration: C:\xampp7\htdocs\desginPattern\phpunit.xml
.
. 2 / 2 (100%)
Time: 93 ms, Memory: 4.00 MB
OK (2 tests, 2 assertions)
sources
https://www.youtube.com/watch?v=LL5MRxpGVGc&list=PLdYYj2XLw5BnpInmR103TyVwFd_CLI6IS&index=5
Comments
Post a Comment