Design Pattern:
Prototype pattern refers to creating duplicate object while keeping performance in mind. This type of design pattern comes under creational pattern as this pattern provides one of the best ways to create an object. 模式:原型模式提供了创建重复对象的最佳方法,属于创建性模式
故事场景:这次不用Curry了,克隆羊多利大家都知道的,只用一个细胞原型就可以无限复制多利羊了
这是一个细胞(细胞可以被克隆的)
public abstract class Cells implements Cloneable { protected String name; public Object clone(){ Object obj = null; try { obj = super.clone(); }catch (CloneNotSupportedException e){ e.printStackTrace(); } return obj; } }复制代码
这是细胞组成的多利羊
public class Dolly extends Cells{ public Dolly(){ name = "Dolly"; } }复制代码
这是细胞克隆工厂,只要你提供原型,你想要的都能克隆
public class CloneFactory { //这是cloneMap 存着需要被克隆的对象 private MapcloneMap = new HashMap<>(); public void loadList(){ Cells cells = new Dolly(); System.out.println("Cache Dolly="+cells); cloneMap.put(cells.name,cells); } //根据名字 clone出你想要的,哈哈 public Cells getObj(String name){ return (Cells)cloneMap.get(name).clone(); } }复制代码
实验的开始
public class PrototypeDemo { public static void main(String[] args) { CloneFactory cache = new CloneFactory(); cache.loadList(); String name = "Dolly"; System.out.println("Clone Dolly="+cache.getObj(name)); } }复制代码