<?php
/**
* Created by PhpStorm.
* User: hzh
* Date: 2018/8/4
* Time: 16:17
*/
/*
* 制定运动接口
*/
interface Sport
{
public function run();
}
/*
* 制定进食接口
*/
interface Eat
{
public function breakfast();
}
/*
* 狗狗类实现运动接口
*/
class DogSport implements Sport
{
public function run()
{
// TODO: Implement run() method.
return "狗狗在运动";
}
}
/*
* 猫猫类实现运动接口
*/
class CatSport implements Sport
{
public function run()
{
// TODO: Implement run() method.
return "猫猫在运动";
}
}
/*
* 狗狗类实现进食接口
*/
class DogEat implements Eat
{
public function breakfast()
{
// TODO: Implement breakfast() method.
return "狗狗吃早餐";
}
}
/*
* 猫猫类实现进食接口
*/
class CatEat implements Eat
{
public function breakfast()
{
// TODO: Implement breakfast() method.
return "猫猫吃早餐";
}
}
/*
* 抽象工厂类
*/
abstract class AbstractFactory
{
abstract protected function getSport($animal);
abstract protected function getEat($animal);
}
/*
* 运动工厂类继承抽象工厂类,并实现获取具体对象的方法
*/
class SportFactory extends AbstractFactory
{
public function getSport($animal)
{
switch($animal)
{
case 'Dog':
return new DogSport();
case 'Cat':
return new CatSport();
}
}
public function getEat($animal)
{
// TODO: Implement getEat() method.
return null;
}
}
/*
* 进食工厂类继承抽象工厂类,并实现获取具体对象的方法
*/
class EatFactory
{
public function getEat($animal)
{
switch($animal)
{
case 'Dog':
return new DogEat();
case 'Cat':
return new CatEat();
}
}
public function getSport($animal)
{
return null;
}
}
/*
* 工厂管理器
*/
class FactoryProducer
{
public function getFactory($factory)
{
switch($factory)
{
case 'Eat':
return new EatFactory();
case 'Sport':
return new SportFactory();
}
}
}
$producer = new FactoryProducer();
$data = [];
$eat = $producer->getFactory('Eat');
$eat_cat = $eat->getEat('Cat');
$data[] = $eat_cat->breakfast();
$sport = $producer->getFactory('Sport');
$sport_dog = $sport->getSport('Dog');
$data[] = $sport_dog->run();
print_r($data);
/*
Array
(
[0] => 猫猫吃早餐
[1] => 狗狗在运动
)
*/
PHP设计模式之抽象工厂模式
猜你喜欢
转载自blog.csdn.net/hhhzua/article/details/81417474
今日推荐
周排行