github地址:https://github.com/1711680493
如需了解更多设计模式,请进入我的设计模式专栏
原型设计模式
将一个对象作为原型,通过对其进行复制而克隆出多个和原型类似的新实例
在Java中将类实现Cloneable接口 以及重写 clone() 方法,来实现别的类对此类的克隆
原型模式实例
在一个游戏中,可以将角色作为原型,角色死亡复活等可以直接替换
/**
* 原型模式
* @author Shendi <a href='tencent://AddContact/?fromId=45&fromSubId=1&subcmd=all&uin=1711680493'>QQ</a>
* @version 1.0
*/
public class Prototype {
//原型
private static PrototypePlayer prototype;
public static void main(String[] args) throws CloneNotSupportedException {
//定义角色
PrototypePlayer player = new PrototypePlayer();
//设置角色属性
player.id = 1;
player.name = "主角";
player.attack = 999;
player.money = 10000;
//将此对象设为原型
prototype = player;
System.out.println("当前对象属性:" + player);
//角色死亡 切换场景 对象重新生成---将之前的原型替换上
player = new PrototypePlayer();
System.out.println("角色死亡...复活,当前属性:" + player);
player = (PrototypePlayer) prototype.clone();
System.out.println("复活完成,当前属性:" + player);
}
}
/**
* 原型类
* @author Shendi <a href='tencent://AddContact/?fromId=45&fromSubId=1&subcmd=all&uin=1711680493'>QQ</a>
* @version 1.0
*/
class PrototypePlayer implements Cloneable {
int id;
String name;
int attack;
int money;
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
@Override
public String toString() {
return "PrototypePlayer [id=" + id + ", name=" + name + ", attack=" + attack + ", money=" + money + "]";
}
}
原型模式应用场景
对象之间相同或相似,即只是个别的几个属性不同的时候
对象的创建过程比较麻烦,但复制比较简单的时候
原型模式的扩展
如果原型对象很多的话,那么可以创建一个Map来管理这些对象