class OrangeDrink{
function getDrinkName()
{
echo '桔子味饮料';
}
}
class FruitFactory{
function makeDrink($fruit){
if ($fruit == 'apple'){
return new AppleDrink();
}elseif ($fruit == 'banana'){
return new BananaDrink();
}elseif ($fruit == 'orange'){
return new OrangeDrink();
}
}
}
<?php
interface Drink{
function getDrinkName();
}
class AppleDrink implements Drink{
function getDrinkName()
{
echo '苹果味饮料';
}
}
class BananaDrink implements Drink{
function getDrinkName()
{
echo '香蕉味饮料';
}
}
interface FruitFactory{
function makeDrink();
}
class AppleFactory implements FruitFactory{
function makeDrink()
{
return new AppleDrink();
}
}
class BananaFactory implements FruitFactory{
function makeDrink()
{
return new BananaDrink();
}
}
$appleFactory = new AppleFactory();
$apple = $appleFactory->makeDrink();
$apple->getDrinkName();
echo "<br/>";
$bananaFactory = new BananaFactory();
$banana = $bananaFactory->makeDrink();
$banana->getDrinkName();
运行结果:
苹果味饮料
香蕉味饮料
现在当再次需要增加桔子味饮料时,只需要增加桔子味饮料产品和桔子味饮料工厂即可,不需要改动原来的代码
class OrangeDrink implements Drink{
function getDrinkName()
{
echo '桔子味饮料';
}
}
class OrangeFactory implements FruitFactory{
function makeDrink()
{
return new OrangeDrink();
}
}