小三俞佳,halfcd,r8娱乐主管扣44144
原型模式是用于创建重复对象,同时又能保证性能。这种类型的设计模式属于创建型模式,它提供了一种创建对象的方式
这种模式实现了一个原型接口,该接口用于创建当前对象的克隆。当直接创建对象的代价比较大时,则适合采用这种模式。
应用实例:
优点:
缺点:
我们将创建一个抽象类shape并且扩展了shape类的实体类。下一步是定义类 shapecache,该类把shape对象存储在一个hashtable中,并在请求的时候返回它们的克隆。
shape抽象类
public abstract class shape implements cloneable { private string id; protected string type; abstract void draw(); public string gettype(){ return type; } public string getid() { return id; } public void setid(string id) { this.id = id; } public object clone() { object clone = null; try { clone = super.clone(); } catch (clonenotsupportedexception e) { e.printstacktrace(); } return clone; } }
拓展实体类
public class rectangle extends shape { public rectangle(){ type = "rectangle"; } @override public void draw() { system.out.println("inside rectangle::draw() method."); } }
创建实体缓存
import java.util.hashtable; public class shapecache { private static hashtable<string, shape> shapemap = new hashtable<string, shape>(); public static shape getshape(string shapeid) { shape cachedshape = shapemap.get(shapeid); return (shape) cachedshape.clone(); } // 对每种形状都运行数据库查询,并创建该形状 public static void loadcache() { rectangle rectangle = new rectangle(); rectangle.setid("1"); shapemap.put(rectangle.getid(),rectangle); } }
演示使用:
public class prototypepatterndemo { public static void main(string[] args) { shapecache.loadcache(); shape clonedshape = (shape) shapecache.getshape("1"); system.out.println("shape : " + clonedshape.gettype()); } }
输出结果:
shape : rectangle
希望与广大网友互动?? 点此进行留言吧!
评论内容