创建型模式
2026/1/15大约 2 分钟
创建型模式
创建型模式关注对象的创建机制,将对象的创建与使用分离。
单例模式
确保一个类只有一个实例,并提供全局访问点。
饿汉式
public class Singleton {
private static final Singleton INSTANCE = new Singleton();
private Singleton() {}
public static Singleton getInstance() {
return INSTANCE;
}
}懒汉式(双重检查锁)
public class Singleton {
private static volatile Singleton instance;
private Singleton() {}
public static Singleton getInstance() {
if (instance == null) {
synchronized (Singleton.class) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}静态内部类
public class Singleton {
private Singleton() {}
private static class Holder {
private static final Singleton INSTANCE = new Singleton();
}
public static Singleton getInstance() {
return Holder.INSTANCE;
}
}枚举(推荐)
public enum Singleton {
INSTANCE;
public void doSomething() {
// ...
}
}单例模式对比
| 方式 | 线程安全 | 延迟加载 | 防止反射攻击 |
|---|---|---|---|
| 饿汉式 | ✓ | ✗ | ✗ |
| 双重检查锁 | ✓ | ✓ | ✗ |
| 静态内部类 | ✓ | ✓ | ✗ |
| 枚举 | ✓ | ✗ | ✓ |
工厂模式
简单工厂
public class ShapeFactory {
public static Shape createShape(String type) {
switch (type) {
case "circle": return new Circle();
case "rectangle": return new Rectangle();
default: throw new IllegalArgumentException();
}
}
}
// 使用
Shape shape = ShapeFactory.createShape("circle");工厂方法
// 抽象工厂
public interface ShapeFactory {
Shape createShape();
}
// 具体工厂
public class CircleFactory implements ShapeFactory {
@Override
public Shape createShape() {
return new Circle();
}
}
public class RectangleFactory implements ShapeFactory {
@Override
public Shape createShape() {
return new Rectangle();
}
}
// 使用
ShapeFactory factory = new CircleFactory();
Shape shape = factory.createShape();抽象工厂
// 抽象工厂
public interface GUIFactory {
Button createButton();
Checkbox createCheckbox();
}
// 具体工厂
public class WindowsFactory implements GUIFactory {
@Override
public Button createButton() {
return new WindowsButton();
}
@Override
public Checkbox createCheckbox() {
return new WindowsCheckbox();
}
}
public class MacFactory implements GUIFactory {
@Override
public Button createButton() {
return new MacButton();
}
@Override
public Checkbox createCheckbox() {
return new MacCheckbox();
}
}工厂模式对比
| 模式 | 特点 | 适用场景 |
|---|---|---|
| 简单工厂 | 一个工厂创建所有产品 | 产品种类少 |
| 工厂方法 | 每个产品一个工厂 | 产品种类多,需要扩展 |
| 抽象工厂 | 创建产品族 | 多个相关产品 |
建造者模式
将复杂对象的构建与表示分离。
public class Computer {
private String cpu;
private String memory;
private String disk;
private Computer(Builder builder) {
this.cpu = builder.cpu;
this.memory = builder.memory;
this.disk = builder.disk;
}
public static class Builder {
private String cpu;
private String memory;
private String disk;
public Builder cpu(String cpu) {
this.cpu = cpu;
return this;
}
public Builder memory(String memory) {
this.memory = memory;
return this;
}
public Builder disk(String disk) {
this.disk = disk;
return this;
}
public Computer build() {
return new Computer(this);
}
}
}
// 使用
Computer computer = new Computer.Builder()
.cpu("Intel i7")
.memory("16GB")
.disk("512GB SSD")
.build();Lombok @Builder
@Builder
@Data
public class Computer {
private String cpu;
private String memory;
private String disk;
}
// 使用
Computer computer = Computer.builder()
.cpu("Intel i7")
.memory("16GB")
.disk("512GB SSD")
.build();原型模式
通过复制现有对象来创建新对象。
浅拷贝
public class Prototype implements Cloneable {
private String name;
private List<String> list;
@Override
public Prototype clone() {
try {
return (Prototype) super.clone();
} catch (CloneNotSupportedException e) {
throw new RuntimeException(e);
}
}
}
// 浅拷贝:list 是同一个引用
Prototype p1 = new Prototype();
Prototype p2 = p1.clone();深拷贝
public class Prototype implements Cloneable {
private String name;
private List<String> list;
@Override
public Prototype clone() {
try {
Prototype clone = (Prototype) super.clone();
clone.list = new ArrayList<>(this.list); // 深拷贝
return clone;
} catch (CloneNotSupportedException e) {
throw new RuntimeException(e);
}
}
}序列化实现深拷贝
public class DeepCopyUtil {
@SuppressWarnings("unchecked")
public static <T extends Serializable> T deepCopy(T obj) {
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(obj);
ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bis);
return (T) ois.readObject();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}