您的位置:首页 > 编程语言 > Java开发

[译]Java 设计模式之原型

2015-01-10 00:14 477 查看
(文章翻译自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()
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: