TL;DR: what do I call a section of code that is used to assemble a Graph object?

I have a fairly large section of code that is duplicated in a few areas. I wish to extract it into its own class. What do I call this class is my question.

The section contains code like this:

    /*
     * First Graph
     */
    $flow_curve = new CurveEntity();
    $curves = array();
    $curves[] = $flow_curve;
    $curves[] = new CurveEntity();
    $curves[] = new CurveEntity();

    $graphs = array();
    $graphs[] = new GraphEntity('graph_1');

    /*
     * Second Graph
     */
    $flow_curve = new CurveEntity($x);
    $curves = array();
    $curves[] = $flow_curve;
    $curves[] = new CurveEntity($y);
    $curves[] = new CurveEntity($z);

    $graphs = array();
    $graphs[] = new GraphEntity('graph_2');

This is not a controller and not view. Is it part of the model? Is it a service? Is it a repository? Nothing seems to fit.

Thinking about what this code represents, it looks like assembly of the $graph object, where the object is later used in the view for graph plotting.

有帮助吗?

解决方案

If the variables $flow_curve, $curves, and $graphs belong to a bigger "something", give that "something" a name and create a class from it (maybe it is the Graph class you mentioned? Or maybe some GraphCollection?). Find an abstraction which suits your needs best. Then the code could be naturally placed in the constructor of that class - and that is the name of the "pattern" you are looking for, if you insist to call it a pattern (personally, I would not).

If, however, the assembling procedure is quite complex, and those variables are just temporary helpers, taking the code out of the constructor into a separate class is the classic Builder design pattern, and the class where the code "lives" may be called GraphBuilder or GraphCollectionBuilder, or similar.

许可以下: CC-BY-SA归因
scroll top