工厂模式
工厂模式主要有四种:简单工厂模式,静态工厂模式,工厂方法模式,抽象工厂模式
简单工厂模式
简单工厂的作用是实例化对象,不需要关心这个对象具体属于哪个子类。子类具有相同的接口或者基类,使用于子类比较固定的情况。
缺陷:如果要增加子类就必须修改工厂,不符合开闭原则
<?php
interface PersonInf
{
public function sex();
public function printSex();
}
class Man implements PersonInf
{
public function sex()
{
return "man";
}
public function printSex()
{
echo "man";
}
}
class Woman implements PersonInf{
public function sex()
{
return "woman";
}
public function printSex()
{
echo "woman";
}
}
class SimpleFactory
{
private $type;
public function __construct()
{
$this->type = array(
'man' => 'Man',
'woman' => 'Woman',
);
}
// 通过方法实例化对象
public function obj($type)
{
return new $this->type[$type];
}
}
$obj = new SimpleFactory();
$child = $obj->obj('woman');
$child->printSex();
静态工厂模式
静态工厂原理基本上跟简单工厂一样,唯一不通的是静态工厂是通过一个静态方法来实例化对象,只要把上面的obj方法改成静态方法就OK了。
工厂方法模式
定义一个创建对象的接口,让子类去实例化具体类。它可以解决简单工厂模式开闭原则。
<?php
interface PersonInf
{
public function create();
}
class Man
{
public function sex()
{
echo "man";
}
}
class Woman
{
public function sex()
{
echo "woman";
}
}
class ManFactory implements PersonInf
{
public function create()
{
return new Man();
}
}
class WomanFactory implements PersonInf
{
public function create()
{
return new Woman();
}
}
class TestFactory{
public function test()
{
$manFactory = new ManFactory();
$man = $manFactory->create();
$man->sex();
$womanFactory = new WomanFactory();
$woman = $womanFactory->create();
$woman->sex();
}
}
$textObj = new TestFactory();
$textObj->test();
抽象工厂模式
抽象工厂模式是为一组相关或者相互依赖的对象提供接口,不需要指定具体实现类。
<?php
interface PersonInf
{
public function createChinese();
public function createJapanese();
public function createAmerican();
}
class Man
{
private $__lang;
public function __construct($lang)
{
$this->__lang = $lang;
}
public function lang()
{
echo $this->__lang;
}
}
class Woman
{
private $__lang;
public function __construct($lang)
{
$this->__lang = $lang;
}
public function lang()
{
echo $this->__lang;
}
}
class ManFactory implements PersonInf
{
public function createChinese()
{
return new Man("汉语");
}
public function createJapanese()
{
return new Man("日语");
}
public function createAmerican()
{
return new Man("英语");
}
}
class WomanFactory implements PersonInf
{
public function createChinese()
{
return new Woman("汉语");
}
public function createJapanese()
{
return new Woman("日语");
}
public function createAmerican()
{
return new Woman("英语");
}
}
class TestFactory{
public function test()
{
$manFactory = new ManFactory();
$man = $manFactory->createChinese();
$man->lang();
$womanFactory = new WomanFactory();
$woman = $womanFactory->createJapanese();
$woman->lang();
}
}
$textObj = new TestFactory();
$textObj->test();