选择正确的模式来使用“;驾驶员”;并将其组合


Choosing the right pattern to use "drivers" and combine it

我是设计模式的新手。我已经在我使用过的框架上使用过它,但现在我需要为我想做的事情选择正确的一个。我的问题是下一个:

我有两个数据库,需要从中提取统计信息。我将称之为loremipsum。在某些情况下,我只需要一个、另一个或两个组合的数据。事实上,我有这样的功能:

  • 获取全部
  • 从Lorem获取所有
  • 从Lipsum获取所有

我认为我可以使用工厂模式来做这样的事情:

<?php
$lorem = Stats::factory('lorem');
$lorem->getAll();
$lipsum = Stats::factory('lipsum');
$lipsum->getAll();

我对这个结构的想法是:

/stats/lorem.php
/stats/lipsum.php
/stats.php

当我制造一个或其他驱动程序时,它将使用另一个文件的getAll。

我认为这是对的。但我也有一个问题。我希望有一些功能可以在内部组合它,比如:

<?php
$all = Stats::factory();
$all->getAll(); // this is lorem and ipsum combined (by me, not auto of course...)

但最后一件事我不知道该如何实现。这个getAll函数将去哪里?

有人能给我一个好方法吗?

提前谢谢!

这个想法是让Stats::factory()方法返回特定接口的对象。在这种情况下,接口将类似于:

interface StatsSource {
    function getAll ();
}

您将有一个实现——"单个数据库"版本,另一个实现是组合结果的组合源版本。这里有一个简单的实现,它只是将两个来源的结果合并在一起。

class SingleDBStatsSource implements StatsSource {
    function __construct ($database) {
        // $database would be the name of the db to use
        // or better yet, a connection to the specific db.
    }
    function getAll ()
    {
        // use databse connection to retrieve all records.
    }        
}

class CombinedStatsSource implements StatsSource {
    function __construct ($statsSourceList) {
        $this->statsSourceList = $statsSourceList;
    }
    function getAll ()
    {
        $results = array();
        foreach ($this->statsSourceList as $statsSource) {
            $results = array_merge($results, $statsSource->getAll());
        }
        return $results;
    }        
}