代码定期设计的设计模式?

时间:2012-03-07 08:58:48

标签: php oop design-patterns modularity

我有这个类尝试多种方法从Google地图Web服务API获取数据。

如果一个方法失败,则尝试另一个方法。等

像这样(伪代码):

FUNCTION FIND_ADDRESS( house_number, postcode )

    get location co-ordinates for postcode from local database

    if location returns false, try getting location from maps service

    if map service fails, return "postcode not found", exit

    get address components using location co-ordinates

    if address components doesn't contain street name, return street name not found, exit

    if street name exists, get all address_components + location for house number, street_name and postcode

    if no results, try again without the postcode,

    if still no results, return location co-ordinates for postcode found earlier in code

END

如您所见,这是非常程序性的!

我正在考虑改进代码的方法,并且我已经将所有可重用的代码外部化,添加了异常处理以确切地知道代码在哪里失败。

但我想知道是否有人知道设计模式或类似解决方案。

因为我基本上是在尝试某些东西,如果它没有尝试别的东西,如果它没有尝试别的东西等等,直到我得到一个完整的地址

有什么想法吗?

5 个答案:

答案 0 :(得分:5)

您可能需要查看Chain of Responsibility.

  

在面向对象设计中,责任链模式是一种设计模式,由命令对象源和一系列处理对象组成。每个处理对象都包含定义它可以处理的命令对象类型的逻辑;其余的传递给链中的下一个处理对象。还存在一种机制,用于将新处理对象添加到该链的末尾。

所以不要使用很多if / else或try / catch块,而是执行类似

的操作
$finderChain = new AddressFinder;
$finder
    ->add(new LocalFinder)
    ->add(new MapsService)
    ->add(…);

$result = $finder->find($houseNo, $postCode);

在内部,您将$ houseNo和$ postCode发送到LocalFinder。如果找不到所需的数据,则链中的下一个元素的任务是尝试查找所需的数据。重复这一过程,直到达到链的末端或产生所需的数据。

答案 1 :(得分:2)

我会尝试像:

public function getAddress($houseNumber,$postCode){

    // as far as i know, if the function returns a LOOSE true, the condition is true
    if($data = location.coordinates()){ 

        // $data was returned a value,  do additional parsing here

        // if you need to return early because of an error, you can in here

        //if all proccesses deem your data valid, return the data you want returned
        if(processedAsValid){
            return $some_value;
        }
    }

    //if the previous didn't return, it goes here. $data is overwritten
    //or you can use some other variable name
    if($data = maps.service()){

        //some more parsing

        return $some_other_data;
    } 

    // if non of the above was satisfied (and thus none returned yet), return a FALSE
    return FALSE;

}

答案 2 :(得分:2)

它不是程序/ oop /无论是什么问题。

如果您轻松理解并维护代码,那就太棒了。如果你能在6个月的时间内完成,那就更好了。

您的功能块看起来很好 - 只需注意您的嵌套深度。越浅越好。

答案 3 :(得分:0)

使用嵌套的try{} catch{}

答案 4 :(得分:-1)

你只有6个“如果”,这根本不是很多,我曾经使用过最多需要50个代码的代码并且程序工作得很好。没有适合您当前问题的软件模式概念。 DP不是特定问题的解决方案,它是一个反复出现问题的解决方案的概念。阅读模式有助于我亲自学习更多解决方案,甚至包括社交问题,编码模式,流程建模,结对编程中的社会问题等等,它提供了许多深思熟虑的想法。

相关问题