建造者模式(Builder Pattern)是一种创建型设计模式,旨在将一个复杂对象的构建过程与其表示分离,以便可以使用相同的构建过程来创建不同的表示。它允许你逐步构建一个复杂对象,同时保持构建过程的灵活性。
建造者模式通常包含以下角色:
建造者模式的主要优点包括:
建造者模式在以下情况下特别有用:
典型的应用场景包括创建文档对象、游戏中的角色创建、配置对象的构建、图形用户界面中的窗口构建以及复杂产品的制造等。建造者模式使得这些场景中的对象构建更灵活、可维护和可扩展。
下面是一个使用Python实现的建造者模式的示例,其中我们创建了一个电脑对象,该电脑具有多个配置选项,如CPU、内存和存储:
# 创建产品类:电脑
class Computer:
def __init__(self):
self.cpu = None
self.memory = None
self.storage = None
def __str__(self):
return f"Computer: CPU={self.cpu}, Memory={self.memory}, Storage={self.storage}"
# 创建抽象建造者接口
class ComputerBuilder:
def set_cpu(self, cpu):
pass
def set_memory(self, memory):
pass
def set_storage(self, storage):
pass
def get_computer(self):
pass
# 创建具体建造者类:高性能电脑建造者
class HighPerformanceComputerBuilder(ComputerBuilder):
def set_cpu(self, cpu):
self.computer.cpu = "High-Performance " + cpu
def set_memory(self, memory):
self.computer.memory = "16GB " + memory
def set_storage(self, storage):
self.computer.storage = "1TB SSD " + storage
def get_computer(self):
return self.computer
# 创建具体建造者类:普通电脑建造者
class StandardComputerBuilder(ComputerBuilder):
def set_cpu(self, cpu):
self.computer.cpu = "Standard " + cpu
def set_memory(self, memory):
self.computer.memory = "8GB " + memory
def set_storage(self, storage):
self.computer.storage = "256GB SSD " + storage
def get_computer(self):
return self.computer
# 创建指导者类:电脑销售员
class ComputerSalesman:
def __init__(self):
self.builder = None
def set_builder(self, builder):
self.builder = builder
def construct_computer(self, cpu, memory, storage):
self.builder.set_cpu(cpu)
self.builder.set_memory(memory)
self.builder.set_storage(storage)
return self.builder.get_computer()
# 客户端代码
if __name__ == "__main__":
salesman = ComputerSalesman()
# 构建高性能电脑
high_performance_builder = HighPerformanceComputerBuilder()
salesman.set_builder(high_performance_builder)
high_performance_computer = salesman.construct_computer("Intel i7", "Corsair", "Samsung")
print(high_performance_computer)
# 构建普通电脑
standard_builder = StandardComputerBuilder()
salesman.set_builder(standard_builder)
standard_computer = salesman.construct_computer("Intel i3", "Kingston", "Seagate")
print(standard_computer)
在这个示例中:
客户端代码演示了如何使用建造者模式来构建不同配置的电脑对象。通过设置不同的建造者,可以构建出高性能电脑和普通电脑,而不需要直接操作产品类的构造函数或属性。这使得创建复杂对象更加灵活和可维护。
建造者模式的实现要素包括以下几个部分:
在这个UML类图中:
上述例子用Java语言实现示例如下:
// 创建产品类:电脑
class Computer {
private String cpu;
private String memory;
private String storage;
public void setCpu(String cpu) {
this.cpu = cpu;
}
public void setMemory(String memory) {
this.memory = memory;
}
public void setStorage(String storage) {
this.storage = storage;
}
@Override
public String toString() {
return "Computer: CPU=" + cpu + ", Memory=" + memory + ", Storage=" + storage;
}
}
// 创建抽象建造者接口
interface ComputerBuilder {
void setCpu();
void setMemory();
void setStorage();
Computer getComputer();
}
// 创建具体建造者类:高性能电脑建造者
class HighPerformanceComputerBuilder implements ComputerBuilder {
private Computer computer = new Computer();
@Override
public void setCpu() {
computer.setCpu("High-Performance Intel i7");
}
@Override
public void setMemory() {
computer.setMemory("16GB Corsair");
}
@Override
public void setStorage() {
computer.setStorage("1TB SSD Samsung");
}
@Override
public Computer getComputer() {
return computer;
}
}
// 创建具体建造者类:普通电脑建造者
class StandardComputerBuilder implements ComputerBuilder {
private Computer computer = new Computer();
@Override
public void setCpu() {
computer.setCpu("Standard Intel i3");
}
@Override
public void setMemory() {
computer.setMemory("8GB Kingston");
}
@Override
public void setStorage() {
computer.setStorage("256GB SSD Seagate");
}
@Override
public Computer getComputer() {
return computer;
}
}
// 创建指导者类:电脑销售员
class ComputerSalesman {
private ComputerBuilder builder;
public void setBuilder(ComputerBuilder builder) {
this.builder = builder;
}
public Computer constructComputer() {
builder.setCpu();
builder.setMemory();
builder.setStorage();
return builder.getComputer();
}
}
// 客户端代码
public class Main {
public static void main(String[] args) {
ComputerSalesman salesman = new ComputerSalesman();
// 构建高性能电脑
ComputerBuilder highPerformanceBuilder = new HighPerformanceComputerBuilder();
salesman.setBuilder(highPerformanceBuilder);
Computer highPerformanceComputer = salesman.constructComputer();
System.out.println(highPerformanceComputer);
// 构建普通电脑
ComputerBuilder standardBuilder = new StandardComputerBuilder();
salesman.setBuilder(standardBuilder);
Computer standardComputer = salesman.constructComputer();
System.out.println(standardComputer);
}
}
上述例子用golang实现示例如下:
package main
import "fmt"
// 创建产品类:电脑
type Computer struct {
CPU string
Memory string
Storage string
}
// 创建抽象建造者接口
type ComputerBuilder interface {
SetCPU()
SetMemory()
SetStorage()
GetComputer() *Computer
}
// 创建具体建造者类:高性能电脑建造者
type HighPerformanceComputerBuilder struct {
computer *Computer
}
func (h *HighPerformanceComputerBuilder) SetCPU() {
h.computer.CPU = "High-Performance Intel i7"
}
func (h *HighPerformanceComputerBuilder) SetMemory() {
h.computer.Memory = "16GB Corsair"
}
func (h *HighPerformanceComputerBuilder) SetStorage() {
h.computer.Storage = "1TB SSD Samsung"
}
func (h *HighPerformanceComputerBuilder) GetComputer() *Computer {
return h.computer
}
// 创建具体建造者类:普通电脑建造者
type StandardComputerBuilder struct {
computer *Computer
}
func (s *StandardComputerBuilder) SetCPU() {
s.computer.CPU = "Standard Intel i3"
}
func (s *StandardComputerBuilder) SetMemory() {
s.computer.Memory = "8GB Kingston"
}
func (s *StandardComputerBuilder) SetStorage() {
s.computer.Storage = "256GB SSD Seagate"
}
func (s *StandardComputerBuilder) GetComputer() *Computer {
return s.computer
}
// 创建指导者类:电脑销售员
type ComputerSalesman struct {
builder ComputerBuilder
}
func (c *ComputerSalesman) SetBuilder(builder ComputerBuilder) {
c.builder = builder
}
func (c *ComputerSalesman) ConstructComputer() *Computer {
c.builder.SetCPU()
c.builder.SetMemory()
c.builder.SetStorage()
return c.builder.GetComputer()
}
func main() {
salesman := &ComputerSalesman{}
// 构建高性能电脑
highPerformanceBuilder := &HighPerformanceComputerBuilder{}
salesman.SetBuilder(highPerformanceBuilder)
highPerformanceComputer := salesman.ConstructComputer()
fmt.Println("High-Performance Computer:")
fmt.Println("CPU:", highPerformanceComputer.CPU)
fmt.Println("Memory:", highPerformanceComputer.Memory)
fmt.Println("Storage:", highPerformanceComputer.Storage)
// 构建普通电脑
standardBuilder := &StandardComputerBuilder{}
salesman.SetBuilder(standardBuilder)
standardComputer := salesman.ConstructComputer()
fmt.Println("\nStandard Computer:")
fmt.Println("CPU:", standardComputer.CPU)
fmt.Println("Memory:", standardComputer.Memory)
fmt.Println("Storage:", standardComputer.Storage)
}
上述例子用javascript实现示例如下:
// 创建产品类:电脑
class Computer {
constructor() {
this.cpu = '';
this.memory = '';
this.storage = '';
}
toString() {
return `Computer: CPU=${this.cpu}, Memory=${this.memory}, Storage=${this.storage}`;
}
}
// 创建抽象建造者类
class ComputerBuilder {
constructor() {
this.computer = new Computer();
}
setCpu(cpu) {
this.computer.cpu = cpu;
}
setMemory(memory) {
this.computer.memory = memory;
}
setStorage(storage) {
this.computer.storage = storage;
}
getComputer() {
return this.computer;
}
}
// 创建具体建造者类:高性能电脑建造者
class HighPerformanceComputerBuilder extends ComputerBuilder {
setCpu() {
this.computer.cpu = 'High-Performance Intel i7';
}
setMemory() {
this.computer.memory = '16GB Corsair';
}
setStorage() {
this.computer.storage = '1TB SSD Samsung';
}
}
// 创建具体建造者类:普通电脑建造者
class StandardComputerBuilder extends ComputerBuilder {
setCpu() {
this.computer.cpu = 'Standard Intel i3';
}
setMemory() {
this.computer.memory = '8GB Kingston';
}
setStorage() {
this.computer.storage = '256GB SSD Seagate';
}
}
// 创建指导者类:电脑销售员
class ComputerSalesman {
constructor() {
this.builder = null;
}
setBuilder(builder) {
this.builder = builder;
}
constructComputer() {
this.builder.setCpu();
this.builder.setMemory();
this.builder.setStorage();
return this.builder.getComputer();
}
}
// 客户端代码
const salesman = new ComputerSalesman();
// 构建高性能电脑
const highPerformanceBuilder = new HighPerformanceComputerBuilder();
salesman.setBuilder(highPerformanceBuilder);
const highPerformanceComputer = salesman.constructComputer();
console.log('High-Performance Computer:');
console.log(highPerformanceComputer.toString());
// 构建普通电脑
const standardBuilder = new StandardComputerBuilder();
salesman.setBuilder(standardBuilder);
const standardComputer = salesman.constructComputer();
console.log('\nStandard Computer:');
console.log(standardComputer.toString());
上述例子用C++实现如下:
#include
#include
// 创建产品类:电脑
class Computer {
public:
std::string cpu;
std::string memory;
std::string storage;
void display() {
std::cout << "Computer: CPU=" << cpu << ", Memory=" << memory << ", Storage=" << storage << std::endl;
}
};
// 创建抽象建造者类
class ComputerBuilder {
public:
virtual void setCpu() = 0;
virtual void setMemory() = 0;
virtual void setStorage() = 0;
virtual Computer* getComputer() = 0;
};
// 创建具体建造者类:高性能电脑建造者
class HighPerformanceComputerBuilder : public ComputerBuilder {
private:
Computer computer;
public:
void setCpu() override {
computer.cpu = "High-Performance Intel i7";
}
void setMemory() override {
computer.memory = "16GB Corsair";
}
void setStorage() override {
computer.storage = "1TB SSD Samsung";
}
Computer* getComputer() override {
return &computer;
}
};
// 创建具体建造者类:普通电脑建造者
class StandardComputerBuilder : public ComputerBuilder {
private:
Computer computer;
public:
void setCpu() override {
computer.cpu = "Standard Intel i3";
}
void setMemory() override {
computer.memory = "8GB Kingston";
}
void setStorage() override {
computer.storage = "256GB SSD Seagate";
}
Computer* getComputer() override {
return &computer;
}
};
// 创建指导者类:电脑销售员
class ComputerSalesman {
private:
ComputerBuilder* builder;
public:
void setBuilder(ComputerBuilder* builder) {
this->builder = builder;
}
Computer* constructComputer() {
builder->setCpu();
builder->setMemory();
builder->setStorage();
return builder->getComputer();
}
};
int main() {
ComputerSalesman salesman;
// 构建高性能电脑
HighPerformanceComputerBuilder highPerformanceBuilder;
salesman.setBuilder(&highPerformanceBuilder);
Computer* highPerformanceComputer = salesman.constructComputer();
std::cout << "High-Performance Computer:" << std::endl;
highPerformanceComputer->display();
// 构建普通电脑
StandardComputerBuilder standardBuilder;
salesman.setBuilder(&standardBuilder);
Computer* standardComputer = salesman.constructComputer();
std::cout << "\nStandard Computer:" << std::endl;
standardComputer->display();
return 0;
}
假设你正在构建一个文本编辑器应用程序。你需要创建一个 Document 类,该类代表文本文档。文档可以包含标题、作者、内容等属性。你需要使用创造者模式来构建文档对象。请完成以下任务:
要求:
示例输出:
Ordinary Document:
Title: My Document
Author: John Doe
Content: This is a regular document.
Important Document:
Title: Important Document
Author: Jane Smith
Content: This is an important document.
你可以在评论区里或者私信我回复您的答案,这样我或者大家都能帮你解答,期待着你的回复~