(文章翻译自Java Design Pattern: Prototype)
原型模式用于当当非常相似的对象频繁被需要的时候。原型模式克隆了对象并且设置变化的特征。这种方式会消耗更少的资源。考虑下为什么会消耗更少的资源?
1.原型模式类图
2.原型模式Java例子
package designpatterns.prototype;
//prototype
interface Prototype {
void setSize(int x);
void printSize();
}
// a concrete class
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();
}
}
//when we need a large number of similar objects
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();
}
}
}
3.原型设计模式在Java表中类库中的使用
java.lang.Object - clone()