vendredi 27 octobre 2017

How to handle complex object creation correctly, even if objects have similar constructors

What is the best design pattern or method for handling complex object creation? Should this pattern change if some objects will have the same constructor?

I have a factory pattern class that contains the required constants to generate the object required. When creating an object, the developer should pass in the constant of their choice. Some of these objects will simply a parent constructor but others might be more complex.

Would the builder design pattern be better here?

class IbmApiRequestTypeBuilder {

    const INSTRUMENT_REQUEST = array("id" => 0,
        "requestUrl" => "/instrument/requestInstrumentList",
        "requestType" => "post",
        "requestBodyHead"=>"RequestInstrumentList",
        "requestBody" => "requestInstrumentList");

    const CREATE_SESSION_REQUEST = array("id" =>1,
        "requestUrl" => "/instrument/requestSession",
        "requestType" => "post",
        "requestBodyHead"=>"requestSession",
        "requestBody"=>"sessionRequest");


    public static function createApiRequestType($type) {

        $requestObj = null;

        switch($type['id']) {
            case 0:
                $requestObj = new IbmApiRequestInstruments($type['requestUrl'],
                $type['requestType'],
                $type['requestBodyHead'],
                $type['requestBody']);
            break;
        case 1:
            $requestObj = new IbmApiRequestSession($type['requestUrl'],
                $type['requestType'],
                $type['requestBodyHead'],
                $type['requestBody']);
            break;
         }

        return $requestObj;
    }
}

Aucun commentaire:

Enregistrer un commentaire