这是Builder模式的正确用法吗

时间:2019-05-23 08:20:57

标签: php laravel design-patterns builder

我有这样的情况:

系统处理来自几个不同来源的预订。所有预订都采用json的形式,每种来源的格式都不同。某些JSON属性存在于一个JSON中,而不存在于其他JSON中。

为了将预订输入到系统中,我试图将“添加预订”逻辑集中到一种方法中。为此,我尝试使用如下构建器模式创建一个名为Reservation的类:

<?php

namespace App\Business\Classes\Reservation;


use App\Business\Classes\Utils\ReservationUtils;

/**
 * Class Reservation
 * Holds entire reservation details
 * @package App\Business\Classes\Reservation
*/
class Reservation
{
    protected $reference, $otaReference, $hotelCode, $customerId, $guestName, $couponId, $checkin, $checkout, $guests, $customerCountry,
    $commissionRate, $paymentStatus, $commissionOta, $commissionDifference, $rooms = [], $cityTax, $vat, $serviceCharge, $geniusBooker = false,
    $geniusAmount = 0, $taxes, $taxIncluded = false, $supplierAmount, $totalAmount, $specialRequest, $currency, $deviceType, $bookingSource,
    $otaRefId, $status, $source, $remarks;

    public function __construct()
    {
        // generates a reference
        $this->reference = ReservationUtils::referenceGenerator();
    }

     /**
      * @param mixed $otaReference
      * @return Reservation
     */
     public function setOtaReference($otaReference): Reservation
     {
        $this->otaReference = $otaReference;
        return $this;
     }

     /**
      * @param mixed $checkin
      * @return Reservation
     */
     public function setCheckin($checkin): Reservation
     {
        $this->checkin = $checkin;
        return $this;
     }

     /**
      * @param mixed $checkout
      * @return Reservation
     */
     public function setCheckout($checkout): Reservation
     {
        $this->checkout = $checkout;
        return $this;
     }

     /**
      * @param array $rooms
      * @return Reservation
     */
     public function setRooms(array $rooms): Reservation
     {
        $this->rooms = $rooms;
        return $this;
     }
     // and so on....
}

我会这样使用它:

$data= json_decode($result->jsonData);
$reservation = (new Reservation())
                  ->setOtaReference($data->otaReference)
                  ->setCheckin($data->checkin)
                  ->setCheckout($data->checkout); //...etc

这可能不是PHP甚至Java中构建器模式在教科书中的用法,但这有什么问题吗?

谢谢

0 个答案:

没有答案