用于处理多样输入以创建对象集合的设计模式
嘿,针对你这个要处理多样输入来创建Variable对象集合的场景,我推荐你组合使用简单工厂模式 + 建造者模式,这俩搭配起来既能优雅处理各种输入源,又能灵活构建你的Collection。下面给你详细拆解:
方案详解
1. 简单工厂:统一处理多样输入,生成Variable对象
既然你有各种不同的输入格式(比如关联数组、JSON字符串、甚至CSV行之类的),把Variable的创建逻辑集中到一个工厂类里是最优解——这样能避免在业务代码里写一堆判断输入类型的if-else,后续新增输入类型也只需要在工厂里加方法,完全符合开闭原则。
示例代码:
class VariableFactory { // 从单个键值对创建Variable public static function fromKeyValue(string $name, mixed $value): Variable { return new Variable($name, $value); } // 从关联数组批量生成Variable数组 public static function fromAssocArray(array $data): array { $variables = []; foreach ($data as $name => $value) { $variables[] = new Variable($name, $value); } return $variables; } // 从JSON字符串生成Variable数组(假设JSON是关联结构) public static function fromJson(string $json): array { $data = json_decode($json, true); if (json_last_error() !== JSON_ERROR_NONE) { throw new InvalidArgumentException('Invalid JSON input'); } return self::fromAssocArray($data); } // 后续可以轻松扩展:比如fromCsvRow()、fromXmlNode()等 }
2. 建造者模式:灵活构建并配置Collection
如果你的Collection需要额外的配置(比如添加前验证、批量添加、甚至预设置排序/过滤规则),建造者模式能让你分步构建集合,而不是一次性塞一堆参数给Collection的构造方法,代码可读性和灵活性会高很多。
示例代码:
class CollectionBuilder { private Collection $collection; private ?callable $validationRule = null; public function __construct() { $this->collection = new Collection(); } // 可选:设置添加项前的验证逻辑 public function withValidation(callable $rule): self { $this->validationRule = $rule; return $this; } // 批量添加Variable对象 public function addVariables(array $variables): self { foreach ($variables as $var) { if ($this->validationRule && !call_user_func($this->validationRule, $var)) { continue; // 也可以抛出异常,根据你的业务需求调整 } $this->collection->addItem($var); } return $this; } // 添加单个Variable对象 public function addVariable(Variable $var): self { if ($this->validationRule && !call_user_func($this->validationRule, $var)) { return $this; } $this->collection->addItem($var); return $this; } // 最终生成配置好的Collection实例 public function build(): Collection { return $this->collection; } }
3. 实际使用示例
// 示例1:从JSON创建带验证的Collection(只允许字符串类型的value) $jsonInput = '{"username": "cyclobster", "email": "test@example.com"}'; $variables = VariableFactory::fromJson($jsonInput); $validatedCollection = (new CollectionBuilder()) ->withValidation(function(Variable $var) { // 这里假设你给Variable类加了getVariableValue()的 getter 方法 return is_string($var->getVariableValue()); }) ->addVariables($variables) ->build(); // 示例2:从关联数组直接创建Collection $arrayInput = ['age' => 30, 'location' => 'New York']; $basicCollection = (new CollectionBuilder()) ->addVariables(VariableFactory::fromAssocArray($arrayInput)) ->build();
为什么选这两个模式?
- 简单工厂:把
Variable的创建逻辑完全抽离,统一管理,后续新增输入类型只需要扩展工厂类,不用修改业务代码,维护起来超方便。 - 建造者模式:让
Collection的构建过程可视化、可配置,你可以按需添加验证规则、选择批量/单个添加,甚至后续扩展排序、过滤的预配置,完全不影响Collection本身的代码。
如果你的输入类型特别多,且不同输入对应不同的“变量组规则”,也可以考虑升级到抽象工厂模式,给每种输入类型单独写工厂类,但对于大多数场景,简单工厂已经足够轻便好用了。
内容的提问来源于stack exchange,提问作者cyclobster
相关产品推荐
相关产品推荐

