原型模式:用原型实例制定创建对象的种类,并且通过拷贝这些原型创建新的对象。
UML 图:
原型类:
package com.cnblog.clarck;
/**
* 原型类
*
* @author clarck
*
*/
public abstract class Prototype {
private String mID;
public Prototype(String id) {
mID = id;
}
public String getID() {
return mID;
}
public abstract Prototype Clone();
}
具体原型类:
package com.cnblog.clarck;
/**
* 要想真正拥有克隆的能力,就需要实现Cloneable接口,重写clone方法。通过克隆方法得到的对象得到的是一个本地的副本
*
* @author clarck
*
*/
public class ConcreatePrototype1 extends Prototype implements Cloneable {
public ConcreatePrototype1(String id) {
super(id);
}
@Override
public Prototype Clone() {
Prototype protoType = null;
try {
protoType = (Prototype) clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return protoType;
}
}
package com.cnblog.clarck;
/**
* 要想真正拥有克隆的能力,就需要实现Cloneable接口,重写clone方法。通过克隆方法得到的对象得到的是一个本地的副本
*
* @author clarck
*
*/
public class ConcreatePrototype2 extends Prototype implements Cloneable {
public ConcreatePrototype2(String id) {
super(id);
}
@Override
public Prototype Clone() {
Prototype protoType = null;
try {
protoType = (Prototype) clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return protoType;
}
}
测试类:
package com.cnblog.clarck;
/**
* 测试类
*
* @author clarck
*
*/
public class Client {
public static void main(String[] args) {
ConcreatePrototype1 p1 = new ConcreatePrototype1("clarck");
ConcreatePrototype1 c1 = (ConcreatePrototype1) p1.Clone();
String str = String.format("id:%s", c1.getID());
System.out.println(str);
ConcreatePrototype1 p2 = new ConcreatePrototype1("clarck2");
ConcreatePrototype1 c2 = (ConcreatePrototype1) p2.Clone();
String str2 = String.format("id:%s", c2.getID());
System.out.println(str2);
}
}