Implement simple factory pattern with PHP code

Guanhui
Release: 2023-04-08 15:14:02
Original
4476 people have browsed it

Implement simple factory pattern with PHP code

PHP code implements simple factory pattern method

1. Define abstract base class

//家禽类
abstract class Fowl
{
	abstract public function eat();//吃方法
}
Copy after login

2. Define subclass

//牛类
class Cattle extends Fowl
{
	public function eat()
	{
		echo "我是牛,我吃草";
	}
}
//鸭类
class Duck extends Fowl
{
	public function eat()
	{
		echo "我是鸭,我吃鱼";
	}
}
//羊类
class Sheep extends Fowl
{
	public function eat()
	{
		echo "我是羊,我吃草";
	}
}
Copy after login

3. Factory class

//工厂类
class Factory
{
	public static function create($fowlName)
	{
		switch ($fowlName) {
			case 'Cattle':
				return new Cattle();
				break;
			case 'Duck':
				return new Duck();
				break;
			case 'Sheep':
				return new Sheep();
				break;
		}
	}
}
Copy after login

4. Client

$cattle = Factory::create('Cattle');
$cattle->eat();//我是牛,我吃草

$duck = Factory::create('Duck');
$duck->eat();//我是鸭,我吃鱼

$sheep = Factory::create('Sheep');
$sheep->eat();//我是羊,我吃草
Copy after login

The above is the detailed content of Implement simple factory pattern with PHP code. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
php
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template