How to implement the factory design pattern in PHP

1 Answer

0 votes
// PHP - Design Patterns - Factory

class Computer
{
    private $OperatingSystem;
    private $ProcessorType;
    private $HardDiskSize;

    public function __construct($OperatingSystem, $ProcessorType, $HardDiskSize)
    {
        $this->OperatingSystem = $OperatingSystem;
        $this->ProcessorType = $ProcessorType;
        $this->HardDiskSize = $HardDiskSize;
    }

    public function getDetails()
    {
        return $this->OperatingSystem . ' - ' .$this->ProcessorType . ' - ' .$this->HardDiskSize;
    }
}

class ComputerFactory
{
    public static function create($OperatingSystem, $ProcessorType, $HardDiskSize)
    {
        return new Computer($OperatingSystem, $ProcessorType, $HardDiskSize);
    }
}

$comp1 = ComputerFactory::create('Windows 10', 'Intel Core i7', '1 TB');
print_r($comp1->getDetails());

echo "<br />";

$comp1 = ComputerFactory::create('OS X Mavericks', 'Intel Core i5', '128 GB');
print_r($comp1->getDetails()); 



/*
run:
  
Windows 10 - Intel Core i7 - 1 TB
OS X Mavericks - Intel Core i5 - 128 GB
 
*/

 



answered Nov 27, 2015 by avibootz

Related questions

...