原型模式定义:用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象。
在运行期需要建立和删除原型,此时可以使用原型模式。
以下代码演示原型模式简单的实际运用:定义一个抽象类Ball:
package com.ldl.cn.PrototypeModel;
public abstract class Ball implements Cloneable{
private String id;
protected String name;
abstract void say();
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Object clone(){
Object cloneObj = null;
try {
cloneObj = super.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return cloneObj;
}
}
分别定义类Baseball、Football继承Ball:
package com.ldl.cn.PrototypeModel;
public class Baseball extends Ball{
public Baseball() {
name = "Baseball";
}
@Override
void say() {
System.out.println("I'm a baseball.");
}
}
package com.ldl.cn.PrototypeModel;
public class Football extends Ball{
public Football() {
name = "Football";
}
@Override
void say() {
System.out.println("I'm a football.");
}
}
编写测试类:
package com.ldl.cn.PrototypeModel;
import java.util.Hashtable;
public class TestPrototypePattern {
private static Hashtable<String, Ball> ballMap = new Hashtable<>();
public static Ball getBall(String id){
Ball ball = ballMap.get(id);
return (Ball) ball.clone();
}
public static void main(String[] args) {
Football football = new Football();
football.setId("1");
ballMap.put(football.getId(), football);
Baseball baseball = new Baseball();
baseball.setId("2");
ballMap.put(baseball.getId(), baseball);
Ball cloneBall1 = ballMap.get("1");
System.out.println("Ball:"+cloneBall1.getName());
Ball cloneBall2 = ballMap.get("2");
System.out.println("Ball:"+cloneBall2.getName());
}
}
运行结果:
Ball:Football
Ball:Baseball