2.5、原型模式

意图
- 用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象
概念
- 适用于:
- 一个系统应该独立于它的产品创建、构成和表示时
- 当要实例化的类是在运行时刻指定时
- 为了避免创建一个与产品类层次平行的工厂类层次时
- 当一个类的实例只能有几个不同的状态组合中的一种时
代码
java
public class main {
public static void main(String[] args) {
Product product1 = new Product();
System.out.println(product1.getId());
Product product2 = (Product) product1.clone();
}
}
interface Prototype {
public Object clone();
}
class Product implements Prototype {
private int id;
private double price;
public Product() {}
public Product(int id, double price) {
this.id = id;
this.price = price;
}
public void getId(int id) {
return id;
}
public void getPrice(double price) {
return price;
}
@override
public Object clone() {
Product product = new Product();
product.id = this.id;
product.price = this.price;
return product;
}
}