创建型模式之原型模式PROTOTYPE

这里写图片描述
意图:用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象。

一、原型模式

原型模式应用场景主要在于当一个对象的创建非常复杂,消耗很多资源之时。如果一个对象的创建之前需要经过很过步骤和要求,一般情况对象用完就会销毁。但为了避免资源的消耗。可以把对象存住,下次使用时直接复制原型。
java 克隆
这里写图片描述

二、代码

原料
主要在于实现java对象的克隆

package prototype;

public abstract class Shape implements Cloneable {

       private String id;
       protected String type;

       abstract void draw();

       public void setId(String id){
           this.id = id;
       }

       public String getId() {
              return id;
       }       

       public Object clone() {
           Shape clone = null;
          try {
             clone = (Shape)super.clone();
          } catch (CloneNotSupportedException e) {
             e.printStackTrace();
          }
          return clone;
       }
}
package prototype;

public class Rectangle extends Shape{

    public Rectangle(){
        type = "Rectangle";
    }

   @Override
   public void draw() {
      System.out.println("Rectangle");
   }

}
package prototype;

public class Square extends Shape {

   public Square(){
         type = "Square";
   }

   @Override
   public void draw() {
      System.out.println("Square");
   }

}

容器

package prototype;

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() {

      Square square = new Square();
      square.setId("1");
      shapeMap.put(square.getId(),square);

      Rectangle rectangle = new Rectangle();
      rectangle.setId("2");
      shapeMap.put(rectangle.getId(),rectangle);

   }

   public static void main(String[] args) {
          ShapeCache.loadCache();

          Shape clonedShape1 = (Shape) ShapeCache.getShape("1");
          System.out.println(clonedShape1.type);        

          Shape clonedShape2 = (Shape) ShapeCache.getShape("2");
          System.out.println(clonedShape2.type);        

    }   

}

代码

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值