建造者模式在产品制作场景中非常适用,尤其是当产品包含多个复杂的组成部分,并且这些组成部分的构建过程需要灵活控制时

建造者模式在产品制作场景中非常适用,尤其是当产品包含多个复杂的组成部分,并且这些组成部分的构建过程需要灵活控制时。下面以制作一款智能手机为例,来说明如何使用建造者模式实现产品制作。

1. 定义产品类(智能手机)

public class Smartphone {
    private String cpu;        // CPU
    private String memory;     // 内存
    private String screen;     // 屏幕
    private String battery;    // 电池
    private String camera;     // 摄像头

    public void setCpu(String cpu) {
        this.cpu = cpu;
    }

    public void setMemory(String memory) {
        this.memory = memory;
    }

    public void setScreen(String screen) {
        this.screen = screen;
    }

    public void setBattery(String battery) {
        this.battery = battery;
    }

    public void setCamera(String camera) {
        this.camera = camera;
    }

    @Override
    public String toString() {
        return "Smartphone{" +
                "cpu='" + cpu + '\'' +
                ", memory='" + memory + '\'' +
                ", screen='" + screen + '\'' +
                ", battery='" + battery + '\'' +
                ", camera='" + camera + '\'' +
                '}';
    }
}

2. 定义抽象建造者类

public abstract class SmartphoneBuilder {
    protected Smartphone smartphone;

    public Smartphone getSmartphone() {
        return smartphone;
    }

    public abstract void buildCpu();
    public abstract void buildMemory();
    public abstract void buildScreen();
    public abstract void buildBattery();
    public abstract void buildCamera();
}

3. 实现具体建造者类

假设我们有两种智能手机:基础版和高级版。

基础版智能手机
public class BasicSmartphoneBuilder extends SmartphoneBuilder {
    public BasicSmartphoneBuilder() {
        smartphone = new Smartphone();
    }

    @Override
    public void buildCpu() {
        smartphone.setCpu("Snapdragon 665");
    }

    @Override
    public void buildMemory() {
        smartphone.setMemory("4GB RAM");
    }

    @Override
    public void buildScreen() {
        smartphone.setScreen("6.5 inches, 720p");
    }

    @Override
    public void buildBattery() {
        smartphone.setBattery("4000mAh");
    }

    @Override
    public void buildCamera() {
        smartphone.setCamera("12MP");
    }
}
高级版智能手机
public class AdvancedSmartphoneBuilder extends SmartphoneBuilder {
    public AdvancedSmartphoneBuilder() {
        smartphone = new Smartphone();
    }

    @Override
    public void buildCpu() {
        smartphone.setCpu("Snapdragon 888");
    }

    @Override
    public void buildMemory() {
        smartphone.setMemory("8GB RAM");
    }

    @Override
    public void buildScreen() {
        smartphone.setScreen("6.7 inches, 1080p");
    }

    @Override
    public void buildBattery() {
        smartphone.setBattery("5000mAh");
    }

    @Override
    public void buildCamera() {
        smartphone.setCamera("48MP");
    }
}

4. 定义指挥者类

public class SmartphoneDirector {
    private SmartphoneBuilder smartphoneBuilder;

    public void setSmartphoneBuilder(SmartphoneBuilder smartphoneBuilder) {
        this.smartphoneBuilder = smartphoneBuilder;
    }

    public Smartphone constructSmartphone() {
        smartphoneBuilder.buildCpu();
        smartphoneBuilder.buildMemory();
        smartphoneBuilder.buildScreen();
        smartphoneBuilder.buildBattery();
        smartphoneBuilder.buildCamera();
        return smartphoneBuilder.getSmartphone();
    }
}

5. 客户端代码

public class Main {
    public static void main(String[] args) {
        // 创建基础版智能手机
        SmartphoneBuilder basicBuilder = new BasicSmartphoneBuilder();
        SmartphoneDirector director = new SmartphoneDirector();
        director.setSmartphoneBuilder(basicBuilder);
        Smartphone basicSmartphone = director.constructSmartphone();
        System.out.println(basicSmartphone);

        // 创建高级版智能手机
        SmartphoneBuilder advancedBuilder = new AdvancedSmartphoneBuilder();
        director.setSmartphoneBuilder(advancedBuilder);
        Smartphone advancedSmartphone = director.constructSmartphone();
        System.out.println(advancedSmartphone);
    }
}

6. 输出结果

运行客户端代码,输出结果如下:

Smartphone{cpu='Snapdragon 665', memory='4GB RAM', screen='6.5 inches, 720p', battery='4000mAh', camera='12MP'}
Smartphone{cpu='Snapdragon 888', memory='8GB RAM', screen='6.7 inches, 1080p', battery='5000mAh', camera='48MP'}

7. 优点

  • 封装性好:将智能手机的构建过程封装在具体的建造者类中,隐藏了构建细节。
  • 易于扩展:新增智能手机型号时,只需添加新的具体建造者类,无需修改现有代码。
  • 便于控制细节:通过指挥者类,可以灵活地控制智能手机的构建过程。

8. 适用场景

建造者模式适用于以下场景:

  • 当需要构建一个复杂对象,且对象的构建过程复杂,包含多个步骤和多个部件时。
  • 当需要隐藏对象的构建细节,只暴露一个简单的接口给客户端时。
  • 当需要构建的对象有多种不同的表示时。

通过建造者模式,可以清晰地分离智能手机的构建过程和表示,使得代码更加模块化、易于维护和扩展。
以下是一个使用建造者模式实现的产品制作系统 Python 程序,展示了如何使用建造者模式创建不同类型的电子产品。这个示例将帮助你理解建造者模式在实际产品制作中的应用。

from abc import ABC, abstractmethod

# 产品:电子产品
class ElectronicProduct:
    def __init__(self):
        self.name = None       # 产品名称
        self.cpu = None        # CPU
        self.ram = None        # 内存
        self.storage = None    # 存储
        self.display = None    # 显示屏
        self.battery = None    # 电池
        self.operating_system = None  # 操作系统
    
    def set_name(self, name):
        self.name = name
    
    def set_cpu(self, cpu):
        self.cpu = cpu
    
    def set_ram(self, ram):
        self.ram = ram
    
    def set_storage(self, storage):
        self.storage = storage
    
    def set_display(self, display):
        self.display = display
    
    def set_battery(self, battery):
        self.battery = battery
    
    def set_operating_system(self, os):
        self.operating_system = os
    
    def show_specifications(self):
        print(f"\n产品名称:{self.name}")
        print(f"CPU:{self.cpu}")
        print(f"内存:{self.ram} GB")
        print(f"存储:{self.storage} GB")
        print(f"显示屏:{self.display} 英寸")
        print(f"电池:{self.battery} mAh")
        print(f"操作系统:{self.operating_system}")
        print("=" * 30)


# 抽象建造者:电子产品建造者
class ProductBuilder(ABC):
    @abstractmethod
    def build_name(self):
        pass
    
    @abstractmethod
    def build_cpu(self):
        pass
    
    @abstractmethod
    def build_ram(self):
        pass
    
    @abstractmethod
    def build_storage(self):
        pass
    
    @abstractmethod
    def build_display(self):
        pass
    
    @abstractmethod
    def build_battery(self):
        pass
    
    @abstractmethod
    def build_operating_system(self):
        pass
    
    @abstractmethod
    def get_product(self):
        pass


# 具体建造者:智能手机建造者
class SmartphoneBuilder(ProductBuilder):
    def __init__(self):
        self.product = ElectronicProduct()
    
    def build_name(self):
        self.product.set_name("超级智能手机")
    
    def build_cpu(self):
        self.product.set_cpu("八核高性能处理器")
    
    def build_ram(self):
        self.product.set_ram(8)
    
    def build_storage(self):
        self.product.set_storage(256)
    
    def build_display(self):
        self.product.set_display(6.7)
    
    def build_battery(self):
        self.product.set_battery(5000)
    
    def build_operating_system(self):
        self.product.set_operating_system("移动操作系统")
    
    def get_product(self):
        return self.product


# 具体建造者:平板电脑建造者
class TabletBuilder(ProductBuilder):
    def __init__(self):
        self.product = ElectronicProduct()
    
    def build_name(self):
        self.product.set_name("高级平板电脑")
    
    def build_cpu(self):
        self.product.set_cpu("六核处理器")
    
    def build_ram(self):
        self.product.set_ram(6)
    
    def build_storage(self):
        self.product.set_storage(128)
    
    def build_display(self):
        self.product.set_display(10.9)
    
    def build_battery(self):
        self.product.set_battery(8000)
    
    def build_operating_system(self):
        self.product.set_operating_system("平板操作系统")
    
    def get_product(self):
        return self.product


# 具体建造者:笔记本电脑建造者
class LaptopBuilder(ProductBuilder):
    def __init__(self):
        self.product = ElectronicProduct()
    
    def build_name(self):
        self.product.set_name("轻薄笔记本电脑")
    
    def build_cpu(self):
        self.product.set_cpu("四核处理器")
    
    def build_ram(self):
        self.product.set_ram(16)
    
    def build_storage(self):
        self.product.set_storage(512)
    
    def build_display(self):
        self.product.set_display(14.0)
    
    def build_battery(self):
        self.product.set_battery(6000)
    
    def build_operating_system(self):
        self.product.set_operating_system("桌面操作系统")
    
    def get_product(self):
        return self.product


# 指挥者:生产线主管
class ProductionLineSupervisor:
    def __init__(self, builder):
        self.builder = builder
    
    def construct_product(self):
        self.builder.build_name()
        self.builder.build_cpu()
        self.builder.build_ram()
        self.builder.build_storage()
        self.builder.build_display()
        self.builder.build_battery()
        self.builder.build_operating_system()
        return self.builder.get_product()


# 客户端代码
if __name__ == "__main__":
    # 生产智能手机
    smartphone_builder = SmartphoneBuilder()
    supervisor = ProductionLineSupervisor(smartphone_builder)
    smartphone = supervisor.construct_product()
    smartphone.show_specifications()
    
    # 生产平板电脑
    tablet_builder = TabletBuilder()
    supervisor.builder = tablet_builder  # 更换建造者
    tablet = supervisor.construct_product()
    tablet.show_specifications()
    
    # 生产笔记本电脑
    laptop_builder = LaptopBuilder()
    supervisor.builder = laptop_builder  # 再次更换建造者
    laptop = supervisor.construct_product()
    laptop.show_specifications()
    
    # 自定义产品(扩展场景)
    class GamingLaptopBuilder(ProductBuilder):
        def __init__(self):
            self.product = ElectronicProduct()
        
        def build_name(self):
            self.product.set_name("游戏笔记本电脑")
        
        def build_cpu(self):
            self.product.set_cpu("八核高性能游戏处理器")
        
        def build_ram(self):
            self.product.set_ram(32)
        
        def build_storage(self):
            self.product.set_storage(1024)
        
        def build_display(self):
            self.product.set_display(15.6)
        
        def build_battery(self):
            self.product.set_battery(7000)
        
        def build_operating_system(self):
            self.product.set_operating_system("游戏专用操作系统")
        
        def get_product(self):
            return self.product
    
    gaming_laptop_builder = GamingLaptopBuilder()
    supervisor.builder = gaming_laptop_builder  # 更换为游戏本建造者
    gaming_laptop = supervisor.construct_product()
    gaming_laptop.show_specifications()

这个实现中,我们定义了:

  1. 产品类(ElectronicProduct):表示电子产品,包含名称、CPU、内存、存储、显示屏、电池和操作系统等属性。
  2. 抽象建造者(ProductBuilder):定义了构建电子产品各个部分的接口。
  3. 具体建造者(SmartphoneBuilder、TabletBuilder、LaptopBuilder):实现了抽象建造者接口,构建不同类型的电子产品。
  4. 指挥者(ProductionLineSupervisor):负责使用建造者构建产品,控制构建过程的顺序。

通过这种设计,我们可以轻松地添加新的产品类型(如示例中的 GamingLaptopBuilder),而不需要修改现有的代码结构。客户端只需要与指挥者和建造者接口交互,不需要了解具体的构建细节。

这个模式的优点在于将复杂对象的构建过程封装在具体建造者中,使得构建过程和表示分离,便于扩展和维护。同时,指挥者类可以确保产品按照固定的顺序和规范进行构建。
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Bol5261

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值