建造者模式中buildpart()方法是否为工厂方法?含解析与示例需求
BuildPart() vs. Factory Method: Clarification Great question—this is a common point of confusion since both patterns involve object creation, but their core responsibilities are distinct. Let's unpack this properly.
First: What's the Factory Method Pattern (per GoF)?
From Gamma et al.'s Design Patterns, the Factory Method is defined as:
Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.
In short: Its sole focus is delegating the choice of which concrete class to instantiate to subclasses, with the goal of decoupling object creation from the code that uses the object.
Is BuildPart() a Factory Method?
No, it isn't. Here's why:
- The Builder pattern's
BuildPart()(or the specificBuildXxxmethods in GoF's examples) exists to assemble components of a complex object incrementally, not just to create objects. Its purpose is to orchestrate the construction process, not to defer instantiation logic. - While a
BuildXxxmethod might create an object (like instantiating aRoomorDoor), that's a side effect of its main job: adding that component to the growing product (e.g., aMaze). Factory Methods, by contrast, are dedicated to object creation as their primary responsibility. - To contrast with Abstract Factory (as you noted): An Abstract Factory is a collection of Factory Methods that create related objects (e.g.,
CreateRoom(),CreateDoor()for a maze). A Builder would use these Factory Methods (or inline creation) to put those objects together into a complete product.
GoF Example of a Builder's BuildXxx Method
From Design Patterns, here's the BuildMaze method from the StandardMazeBuilder class—this is part of the Builder's interface for constructing a maze:
void StandardMazeBuilder::BuildMaze () { _currentMaze = new Maze; }
This method initializes the empty maze that will later be populated by other BuildRoom(int), BuildDoor(int, int) methods. Notice that while it creates a Maze instance, its role is to kick off the construction of the complex object (the maze), not to defer instantiation logic to subclasses (which is the Factory Method's job). A subclass of StandardMazeBuilder might change how the maze is assembled, not just what class of maze is created.
Quick Summary
Factory Methods are all about who creates the object, while Builder's BuildPart() methods are all about how the object is put together. They can overlap in implementation (both might create objects), but their design goals and responsibilities are fundamentally different.
内容的提问来源于stack exchange,提问作者Tim

