创建型设计模式
Contents
概念
简单来说就是用来创建对象的设计模式,主要的特点是将对象的创建于使用分离。
简单工厂
定义一个类(工厂类)来负责创建其他类。根据不同的参数返回不同类的实例。
interface Computer
{
public function describe();
}
class Hasee implements Computer
{
public function describe()
{
print_r('神舟电脑');
}
}
class Macbook implements Computer
{
public function describe()
{
print_r('苹果电脑');
}
}
class Fatory
{
public function create($type)
{
if ($type === 'hasee') {
return new Hasee();
} else if ($type === 'hasee') {
return new Macbook();
}
return null;
}
}
工厂方法
interface Computer
{
public function describe();
}
class Hasee implements Computer
{
public function describe()
{
print_r('神舟电脑');
}
}
class Macbook implements Computer
{
public function describe()
{
print_r('苹果电脑');
}
}
interface Factory
{
public function create();
}
class HaseeFactory implements Factory
{
public function create()
{
return new Hasee();
}
}
class MacbookFactory implements Factory
{
public function create()
{
return new Macbook();
}
}
抽象工厂
在工产方法中一个工产方法是生成一个对象,抽象工厂则是生产一类的对象
interface Computer
{
public function describe();
}
class Hasee implements Computer
{
public function describe()
{
print_r('神舟电脑');
}
}
class Lenovo implements Computer
{
public function describe()
{
print_r('联想电脑');
}
}
class Macbook implements Computer
{
public function describe()
{
print_r('苹果电脑');
}
}
interface Factory
{
public function create($type);
}
class MacFactory implements Factory
{
public function create($type)
{
if ($type === 'mac') {
return new Macbook();
}
return null;
}
}
class WindowFactory implements Factory
{
public function create($type)
{
if ($type === 'lenovo') {
return new Lenovo();
} else if ($type === 'hasee') {
return new Hasee();
}
return null;
}
}
单例
class Single
{
private static Single $instance;
final private function __construct()
{
}
final private function __clone()
{
}
public static function getInstance()
{
if (!self::$instance) {
self::$instance = new self();
}
return self::instance;
}
}
建造者
它将一个复杂对象的创建于它的表示分离,可以通过设置不同的参数来构建对象。
class Builder
{
public $color;
public $cpu;
public function setColor($color)
{
$this->color = $color;
return $this;
}
public function setCpu($cpu)
{
$this->cpu = $cpu;
return $this;
}
public function build()
{
return new Computer($this);
}
}
class Computer
{
private $builder;
public function __construct(Builder $builder)
{
$this->builder = $builder;
}
}
$builder = new Builder();
$computer = $builder->setColor('red')->setCpu('i7')->build();
原型模式
通过复制原型来创建对象
class Hasee implements Computer
{
public function describe()
{
print_r('神舟电脑');
}
}
$hasee = new Hasee();
$haseeCopy = clone $hasee;