原型模式(Prototype Pattern)

2024/3/27 Java进阶

原型模式就是深克隆。

# 1、原型模式案例

public abstract class Prototype {
    abstract Prototype cloneAll();
}
1
2
3
@Getter
public class Product extends Prototype{
    private String productName;

    public Product(String productName) {
        this.productName = productName;
    }

    @Override
    Prototype cloneAll() {
        return new Product(productName);
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
public class ClientTest {
    public static void main(String[] args) {
        Product product = new Product("手机");
        Product cloneProduct = (Product) product.cloneAll();

        System.out.println((product==cloneProduct)+":"+cloneProduct.getProductName());
    }
}

// 输出结果:false:手机
1
2
3
4
5
6
7
8
9
10