工厂模式极速入门课程总结

原创 2018-12-26 15:46:55 620
摘要:工厂模式:根据用户需求,动态生成类的实例//先创建二个类 class Computer { public function work() { return '可以学习编程'; } } class Auto { public function run() { return '可

工厂模式:根据用户需求,动态生成类的实例

//先创建二个类
class Computer
{
	public function work()
	{
		return '可以学习编程';
	}
}

class Auto
{
	public function run()
	{
		return '可以带着我到处玩';
	}
}
//1.创建工厂类: Factory
class Factory
{
	public static function create($className)
	{
		switch (strtolower($className)) {
			case 'computer':
				return new Computer();
				break;
			case 'auto':
				return new Auto();
				break;
		}
	}
}

class Student
{
	public function study()
	{
		$computer = Factory::create('Computer');
		return '计算机'.$computer-> work();
	}

	public function drive()
	{
		$auto = Factory::create('Auto');;
		return '汽车'.$auto->run();
	}
}

$student = new Student;
echo $student->study();
echo '<br>';
echo $student->drive();
发布手记

热门词条