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

Ale*_*nch 3 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
Run Code Online (Sandbox Code Playgroud)

如你所见,这是非常程序化的!

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

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

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

有任何想法吗?

Gor*_*don 5

您可能想要查看责任链.

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

因此,不要使用很多if/else或try/catch块,而是执行类似的操作

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

$result = $finder->find($houseNo, $postCode);
Run Code Online (Sandbox Code Playgroud)

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