一、定义

用原型实例指定创建对象的类型,并通过复制这个原型创建一个新对象。

二、类图表示

原型模式

三、实现

  • Prototype
package pattern.creational.prototype;

public abstract class Prototype {

	private String id;
	private String type;
	public Prototype(String id) {
		this.id = id;
	}
	public String getId() {
		return id;
	}
	public String getType() {
		return type;
	}
	public void setType(String type) {
		this.type = type;
	}
	@Override
	public String toString() {
		return String.format("TYPE: %s  Identity Id: %s", this.getType(), this.getId());
	}
	public abstract Prototype clone();
}

  • ConcretePrototype
package pattern.creational.prototype;

public class ConcretePrototypeA extends Prototype {

	public ConcretePrototypeA(String id) {
		super(id);
		setType("ALPHA");
	}

	@Override
	public Prototype clone() {
		return new ConcretePrototypeA(this.getId());
	}
}


package pattern.creational.prototype;

public class ConcretePrototypeB extends Prototype {

	public ConcretePrototypeB(String id) {
		super(id);
		setType("BRAVO");
	}

	@Override
	public Prototype clone() {
		return new ConcretePrototypeB(this.getId());
	}

}

四、使用

package pattern.creational.prototype;

public class Client {

	public static void main(String[] args) {
		Prototype pa = new ConcretePrototypeA("A");
		Prototype ca = pa.clone();
		System.out.println(ca);
		
		Prototype pb = new ConcretePrototypeB("B");
		Prototype cb = pb.clone();
		System.out.println(cb);
	}
}

  • 输出

TYPE: ALPHA Identity Id: A

TYPE: BRAVO Identity Id: B

五、适用场合

  • 当要实例化的类是在运行时指定时
  • 产生对象的过程比较复杂,初始化需要很多资源时
  • 同一个对象可能会供多个调用者同时调用时