天天看点

PHP中的工厂方法模式

php手册中的工厂方法

•使用工厂来替换new操作

•思路:动态的根据传递的数据,新建相应的类的对象。

•<?php

class example

{

    // the parameterized factory method

    public static function factory(type)     {         if (include_once 'drivers/' .type)     {         if (include_once 'drivers/' .type . '.php') {

            classname = 'driver_' .classname = 'driver_' .type;

            return new $classname;

        } else {

            throw new exception('driver not found');

        }

    }

}

?>

// load a mysql driver

mysql=example::factory(′mysql′);//loadansqlitedrivermysql=example::factory(′mysql′);//loadansqlitedriversqlite = example::factory('sqlite');

gof的工厂方法模式

•简单工厂模式---工厂方法模式

•工厂方法模式是创建型模式的一种

•意图:定义一个用于创建对象的接口,让子类决定实例化哪一个类。工厂方法模式能使一个类的实例化延迟到其子类。

PHP中的工厂方法模式

工厂方法实现

适用的需求

•1 生成”简历”或者”报告”两种文档格式

•2 简历文档页面:

–技能页 + 教育经历页 + 工作经历页

•3 报告文档页面:

–介绍页面 + 阐述结论页面 + 总结页

•4 以后很有可能增加新的文档格式,新的文档格式可能会有新的文档页面

•1 创建document类

•2 创建继承于document的report类和resume类

•3 创建page类

•4 创建继承于page的skillspage,educationpage,experiencepage类

•5 创建继承于page的introductionpage,resultpage,summarypage类

•document类的实现

PHP中的工厂方法模式

•resume类实现

PHP中的工厂方法模式

•program

PHP中的工厂方法模式