当经常创建非常相似的对象时,使用原型设计模式。原型模式将克隆对象并设置更改的功能。这样,消耗的资源更少。
1.原型模式类图
2.原型模式Java示例
package designpatterns.prototype;
//prototype
interface Prototype {
void setSize(int x);
void printSize();
}
//一个具体的类
class A implements Prototype, Cloneable {
private int size;
public A(int x) {
this.size = x;
}
@Override
public void setSize(int x) {
this.size = x;
}
@Override
public void printSize() {
System.out.println("Size: " + size);
}
@Override
public A clone() throws CloneNotSupportedException {
return (A) super.clone();
}
}
///当我们需要大量类似的对象时,
public class PrototypeTest {
public static void main(String args[]) throws CloneNotSupportedException {
A a = new A(1);
for (int i = 2; i < 10; i++) {
Prototype temp = a.clone();
temp.setSize(i);
temp.printSize();
}
}
}
- Java标准库中使用的原型设计模式
java.lang.Object-clone()