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');
        }
    }
}
?>

•<?php
// 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中的工厂方法模式

上一篇:表格的半透明显示效果


下一篇:数论 - 素数的运用 --- poj 2689 : Prime Distance