当前位置: 移动技术网 > IT编程>开发语言>Java > 设计模式之原型模式——Java语言描述

设计模式之原型模式——Java语言描述

2019年01月05日  | 移动技术网IT编程  | 我要评论
原型模式是用于创建重复对象,同时又能保证性能。这种类型的设计模式属于创建型模式,它提供了一种创建对象的方式 ...

原型模式是用于创建重复对象,同时又能保证性能。这种类型的设计模式属于创建型模式,它提供了一种创建对象的方式

这种模式实现了一个原型接口,该接口用于创建当前对象的克隆。当直接创建对象的代价比较大时,则适合采用这种模式。

应用实例:

  1. 细胞分裂
  2. java中的object.clone()方法

优点:

  1. 性能较高
  2. 逃避构造函数的约束

缺点:

  1. 配备克隆方法需要对类的功能进行通盘考虑,这对于全新的类不是很难,但对于已有的类不一定很容易,特别当一个类引用不支持串行化的间接对象,或者引用含有循环结构的时候。
  2. 必须实现 cloneable 接口。

实现

我们将创建一个抽象类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

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网