GoF:Prototype模式

1.意图:

 用原型实例制定创建对象的种类,并且通过拷贝这些原型创建新的对象。(G4)

例子:

public abstract class AbstractPrototype implements Cloneable{
	@Override
	protected Object clone(){
		Object o=null;
		try {
			o=super.clone();
		} catch (CloneNotSupportedException e) {
			e.printStackTrace();
		}
		return o;
	}
	public abstract void say();
	public String getStrName() {
		return strName;
	}
	public void setStrName(String strName) {
		this.strName = strName;
	}
	private String strName;
}

public class PrototypeA extends AbstractPrototype {

	public PrototypeA(String name) {
		setStrName(name);
	}
	@Override
	public void say() {
		System.out.println("PrototypeA");
	}
}

public class PrototypeB extends AbstractPrototype {
	public PrototypeB(String name) {
		setStrName(name);
	}
	@Override
	public void say() {
		System.out.println("PrototypeB");
	}
}

public class Test {
	public static void main(String[] agrs) {
		AbstractPrototype p = new PrototypeA("fy");
		AbstractPrototype k = (AbstractPrototype) p.clone();
		AbstractPrototype e = (AbstractPrototype) p.clone();
		p.say();
		k.say();
		e.say();
		AbstractPrototype q = new PrototypeB("flh");
		AbstractPrototype c = (AbstractPrototype) q.clone();
		AbstractPrototype u = (AbstractPrototype) q.clone();
		q.say();
		c.say();
		u.say();
	}
}

    运行结果:

PrototypeA
PrototypeA
PrototypeA
PrototypeB
PrototypeB
PrototypeB

 

你可能感兴趣的:(C++,c,prototype,C#)