一、构造器实例化(最基础)

1. public 构造器

public class User {
    private String name;
    private int age;
    
    public User() {}  // 无参构造
    public User(String name, int age) {  // 有参构造
        this.name = name;
        this.age = age;
    }
}

// 使用
User user1 = new User();
User user2 = new User("张三", 25);
特性说明
优点简单直接,语法简洁,性能最好
缺点参数多时代码可读性差,缺乏灵活性
适用场景简单POJO、DTO、实体类,参数少且固定

2. private 构造器 + 静态工厂方法

public class User {
    private String name;
    private int age;
    
    private User() {}  // 私有构造器
    
    public static User createDefault() {
        return new User();  // 静态工厂方法
    }
    
    public static User createWithName(String name) {
        User user = new User();
        user.name = name;
        return user;
    }
}

// 使用
User user1 = User.createDefault();
User user2 = User.createWithName("张三");
特性说明
优点有意义的方法名,可控制实例数量,可返回子类型
缺点不能继承,API略复杂
适用场景单例、工具类、需要命名的实例化

二、建造者模式(Builder Pattern)

3. 经典 Builder

public class Computer {
    private String cpu;
    private String ram;
    private String graphicsCard;
    private String hardDisk;
    
    private Computer(Builder builder) {
        this.cpu = builder.cpu;
        this.ram = builder.ram;
        this.graphicsCard = builder.graphicsCard;
        this.hardDisk = builder.hardDisk;
    }
    
    public static class Builder {
        private String cpu;  // 必填
        private String ram;  // 必填
        private String graphicsCard = "集成显卡";  // 可选,有默认值
        private String hardDisk = "512GB";  // 可选
        
        public Builder(String cpu, String ram) {
            this.cpu = cpu;
            this.ram = ram;
        }
        
        public Builder graphicsCard(String graphicsCard) {
            this.graphicsCard = graphicsCard;
            return this;
        }
        
        public Builder hardDisk(String hardDisk) {
            this.hardDisk = hardDisk;
            return this;
        }
        
        public Computer build() {
            return new Computer(this);
        }
    }
}

// 使用
Computer computer = new Computer.Builder("i7", "16GB")
    .graphicsCard("RTX 3080")
    .hardDisk("1TB SSD")
    .build();
特性说明
优点代码可读性高,参数灵活,支持不可变对象,参数校验集中
缺点代码量大,有性能开销(创建Builder对象)
适用场景参数多(>4个)、有大量可选参数、需要创建不可变对象

4. Lombok @Builder

import lombok.Builder;
import lombok.Singular;
import java.util.List;

@Builder
public class Order {
    private String orderNo;
    private double amount;
    private String userId;
    @Singular  // 处理集合的特殊注解
    private List<String> items;
}

// 使用
Order order = Order.builder()
    .orderNo("NO2024001")
    .amount(299.99)
    .userId("U12345")
    .item("商品1")  // @Singular 允许这样添加
    .item("商品2")
    .build();
特性说明
优点代码极少,自动生成,维护方便
缺点需引入Lombok依赖,定制性不如手动Builder
适用场景大多数需要Builder的场景,特别是简单对象

三、工厂模式

5. 简单工厂

public interface Animal {
    void speak();
}

public class Dog implements Animal {
    public void speak() { System.out.println("Woof"); }
}

public class Cat implements Animal {
    public void speak() { System.out.println("Meow"); }
}

public class AnimalFactory {
    public static Animal createAnimal(String type) {
        if ("dog".equalsIgnoreCase(type)) {
            return new Dog();
        } else if ("cat".equalsIgnoreCase(type)) {
            return new Cat();
        }
        throw new IllegalArgumentException("Unknown animal type");
    }
}

// 使用
Animal animal = AnimalFactory.createAnimal("dog");
特性说明
优点封装创建逻辑,客户端与具体类解耦
缺点添加新产品需修改工厂类,违反开闭原则
适用场景产品种类少且稳定,创建逻辑简单

6. 工厂方法模式

public abstract class Dialog {
    public void render() {
        Button okButton = createButton();
        okButton.render();
    }
    protected abstract Button createButton();  // 工厂方法
}

public class WindowsDialog extends Dialog {
    @Override
    protected Button createButton() {
        return new WindowsButton();
    }
}

public class WebDialog extends Dialog {
    @Override
    protected Button createButton() {
        return new HtmlButton();
    }
}

// 使用
Dialog dialog = new WindowsDialog();
dialog.render();  // 创建Windows风格的按钮
特性说明
优点符合开闭原则,扩展性好,解耦度高
缺点类的数量增加,系统复杂度提高
适用场景框架设计、需要扩展性的系统、产品族概念

7. 抽象工厂模式

public interface GUIFactory {
    Button createButton();
    Checkbox createCheckbox();
}

public class WindowsFactory implements GUIFactory {
    public Button createButton() { return new WindowsButton(); }
    public Checkbox createCheckbox() { return new WindowsCheckbox(); }
}

public class MacFactory implements GUIFactory {
    public Button createButton() { return new MacButton(); }
    public Checkbox createCheckbox() { return new MacCheckbox(); }
}

// 使用
GUIFactory factory = new WindowsFactory();
Button button = factory.createButton();  // Windows风格
Checkbox checkbox = factory.createCheckbox();  // Windows风格
特性说明
优点保证产品族的一致性,易于交换产品系列
缺点添加新产品困难,需修改抽象工厂接口
适用场景系统需要多个产品系列,产品之间有约束关系

四、原型模式(克隆)

8. Cloneable 方式

public class Document implements Cloneable {
    private String title;
    private String content;
    private List<String> authors;
    
    @Override
    public Document clone() {
        try {
            Document cloned = (Document) super.clone();
            // 深拷贝
            cloned.authors = new ArrayList<>(this.authors);
            return cloned;
        } catch (CloneNotSupportedException e) {
            throw new RuntimeException(e);
        }
    }
}

// 使用
Document original = new Document();
original.setTitle("设计模式");
// ... 设置其他属性
Document copy = original.clone();  // 克隆,不是new
特性说明
优点性能高(特别是复杂对象),避免重复初始化
缺点深拷贝实现复杂,Cloneable接口是标记接口
适用场景对象创建成本高、需要大量相似对象

9. 拷贝构造器

public class Person {
    private String name;
    private int age;
    private List<String> hobbies;
    
    // 拷贝构造器
    public Person(Person other) {
        this.name = other.name;
        this.age = other.age;
        this.hobbies = new ArrayList<>(other.hobbies);  // 深拷贝
    }
}

// 使用
Person person1 = new Person("张三", 25, Arrays.asList("读书", "运动"));
Person person2 = new Person(person1);  // 通过拷贝构造器创建
特性说明
优点类型安全,实现简单,可控制拷贝深度
缺点需为每个类编写拷贝构造器
适用场景需要提供拷贝功能,且希望类型安全的场景

五、依赖注入

10. Spring IoC 容器

@Component
public class UserService {
    @Autowired
    private UserRepository userRepository;
    
    public User findUser(Long id) {
        return userRepository.findById(id).orElse(null);
    }
}

// 使用(由Spring管理,不需要new)
@Service
public class UserController {
    @Autowired
    private UserService userService;
}
特性说明
优点解耦,便于测试,管理对象生命周期
缺点增加框架依赖,学习成本,启动慢
适用场景大型应用,需要解耦和便于测试的场景

六、性能对比

实例化方式性能内存占用代码量灵活性
new 构造器⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐
静态工厂⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐
Builder⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐
Lombok Builder⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐
工厂模式⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐
原型模式⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐
DI容器⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐

七、选择指南

根据参数数量选择

// 0-2个参数:直接使用构造器
new User("张三", 25);

// 3-4个参数:考虑用静态工厂或简单Builder
User.createWithNameAndAge("张三", 25);

// 5个以上参数:必须用Builder
new User.Builder("i7", "16GB")
    .graphicsCard("RTX 3080")
    .hardDisk("1TB")
    .monitor("4K")
    .build();

根据场景选择

// 场景1:简单的数据传输对象
public class LoginRequest {
    private String username;
    private String password;
    // 直接用构造器或Lombok @Data
}

// 场景2:配置对象
public class DatabaseConfig {
    private String host;
    private int port;
    private String username;
    private String password;
    private int maxConnections;
    private int timeout;
    private boolean ssl;
    // 用Builder
}

// 场景3:框架扩展点
public interface Plugin {
    void init();
}
// 用工厂模式创建插件实例

快速决策树

开始
  ↓
需要创建对象?
  ↓
  ├→ 参数很少(≤2) → 用构造器
  ↓
参数很多(≥4)?
  ↓
  ├→ 对象可变 → 用setter方式
  ├→ 对象不可变 → 用Builder
  ↓
需要控制实例数量?
  ↓
  ├→ 单例 → 静态工厂 + private构造器
  ├→ 池化 → 工厂模式
  ↓
需要根据条件创建不同子类?
  ↓
  ├→ 用工厂模式
  ↓
需要复制相似对象?
  ↓
  ├→ 用原型模式

八、最佳实践总结

/**
 * 最佳实践示例
 */
public class BestPractices {
    
    // 1. 简单对象:用构造器
    public class User {
        private String name;
        private int age;
        public User(String name, int age) {
            this.name = name;
            this.age = age;
        }
    }
    
    // 2. 复杂对象:用Builder
    @Builder
    public class Configuration {
        private String host;
        private int port;
        private String username;
        private String password;
        private int timeout;
        private boolean ssl;
    }
    
    // 3. 需要扩展性:用工厂
    public interface PaymentService {
        void pay(double amount);
    }
    
    public class PaymentServiceFactory {
        public static PaymentService create(String type) {
            if ("alipay".equals(type)) return new AlipayService();
            if ("wechat".equals(type)) return new WechatPayService();
            throw new IllegalArgumentException();
        }
    }
    
    // 4. 单例:静态工厂
    public class DatabasePool {
        private static DatabasePool instance;
        private DatabasePool() { }
        public static synchronized DatabasePool getInstance() {
            if (instance == null) {
                instance = new DatabasePool();
            }
            return instance;
        }
    }
}

核心原则:

  • 简单优先:能用构造器就别用复杂模式
  • 可读性优先:Builder能大幅提升代码可读性时就用
  • 扩展性考虑:预见可能的变化,选择合适的设计模式
Logo

汇聚全球AI编程工具,助力开发者即刻编程。

更多推荐