一、构造器实例化(最基础)
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")
.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();
| 特性 | 说明 |
|---|
| 优点 | 符合开闭原则,扩展性好,解耦度高 |
| 缺点 | 类的数量增加,系统复杂度提高 |
| 适用场景 | 框架设计、需要扩展性的系统、产品族概念 |
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();
Checkbox checkbox = factory.createCheckbox();
| 特性 | 说明 |
|---|
| 优点 | 保证产品族的一致性,易于交换产品系列 |
| 缺点 | 添加新产品困难,需修改抽象工厂接口 |
| 适用场景 | 系统需要多个产品系列,产品之间有约束关系 |
四、原型模式(克隆)
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();
| 特性 | 说明 |
|---|
| 优点 | 性能高(特别是复杂对象),避免重复初始化 |
| 缺点 | 深拷贝实现复杂,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);
}
}
@Service
public class UserController {
@Autowired
private UserService userService;
}
| 特性 | 说明 |
|---|
| 优点 | 解耦,便于测试,管理对象生命周期 |
| 缺点 | 增加框架依赖,学习成本,启动慢 |
| 适用场景 | 大型应用,需要解耦和便于测试的场景 |
六、性能对比
| 实例化方式 | 性能 | 内存占用 | 代码量 | 灵活性 |
|---|
| new 构造器 | ⭐⭐⭐⭐⭐ | ⭐⭐⭐⭐⭐ | ⭐⭐⭐⭐⭐ | ⭐⭐ |
| 静态工厂 | ⭐⭐⭐⭐ | ⭐⭐⭐⭐ | ⭐⭐⭐⭐ | ⭐⭐⭐ |
| Builder | ⭐⭐⭐ | ⭐⭐⭐ | ⭐⭐ | ⭐⭐⭐⭐⭐ |
| Lombok Builder | ⭐⭐⭐ | ⭐⭐⭐ | ⭐⭐⭐⭐⭐ | ⭐⭐⭐⭐ |
| 工厂模式 | ⭐⭐⭐ | ⭐⭐⭐ | ⭐⭐⭐ | ⭐⭐⭐⭐ |
| 原型模式 | ⭐⭐⭐⭐ | ⭐⭐⭐ | ⭐⭐⭐ | ⭐⭐⭐ |
| DI容器 | ⭐⭐ | ⭐⭐ | ⭐⭐⭐⭐ | ⭐⭐⭐⭐⭐ |
七、选择指南
根据参数数量选择
new User("张三", 25);
User.createWithNameAndAge("张三", 25);
new User.Builder("i7", "16GB")
.graphicsCard("RTX 3080")
.hardDisk("1TB")
.monitor("4K")
.build();
根据场景选择
public class LoginRequest {
private String username;
private String password;
}
public class DatabaseConfig {
private String host;
private int port;
private String username;
private String password;
private int maxConnections;
private int timeout;
private boolean ssl;
}
public interface Plugin {
void init();
}
快速决策树
开始
↓
需要创建对象?
↓
├→ 参数很少(≤2) → 用构造器
↓
参数很多(≥4)?
↓
├→ 对象可变 → 用setter方式
├→ 对象不可变 → 用Builder
↓
需要控制实例数量?
↓
├→ 单例 → 静态工厂 + private构造器
├→ 池化 → 工厂模式
↓
需要根据条件创建不同子类?
↓
├→ 用工厂模式
↓
需要复制相似对象?
↓
├→ 用原型模式
八、最佳实践总结
public class BestPractices {
public class User {
private String name;
private int age;
public User(String name, int age) {
this.name = name;
this.age = age;
}
}
@Builder
public class Configuration {
private String host;
private int port;
private String username;
private String password;
private int timeout;
private boolean ssl;
}
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();
}
}
public class DatabasePool {
private static DatabasePool instance;
private DatabasePool() { }
public static synchronized DatabasePool getInstance() {
if (instance == null) {
instance = new DatabasePool();
}
return instance;
}
}
}
核心原则:
- 简单优先:能用构造器就别用复杂模式
- 可读性优先:Builder能大幅提升代码可读性时就用
- 扩展性考虑:预见可能的变化,选择合适的设计模式
所有评论(0)