java父原型_java设计模式(七)--原型模式

抽象的父类通过实现Cloneable接口,继而重写接口中的clone方法,然后让各个实体类继承此父类,之后再建立一个拥有获取实体类的克隆体的方法的类,通过第一次new对象之后,再创建对对象的时候就不用再new了,而是将之前的对象克隆即可,这样省去了new对象的步骤,在运行阶段才能确定实例的时候使用这种设计模式。

网络上的专业解释: 这种模式实现了一个原型接口,该接口用于创建当前对象的克隆。当直接创建对象的代价比较大时,则采用这种模式。例如,一个对象需要在一个高代价的数据库操作之后被创建。我们可以缓存该对象,在下一个请求时返回他的克隆,在需要的时候更新数据库,以次来减少数据库的调用。

实例:用原型模式完成对多个圆形和矩形的创建:

a436cda07050affef9d80c75dec2ce44.png

1)抽象父类的创建(必实现Cloneable接口)

public abstract class Shape implements Cloneable {

private String id;

protected String type;

public String getId() {

return id;

}

public void setId(String id) {

this.id = id;

}

public String getType() {

return type;

}

public void setType(String type) {

this.type = type;

}

abstract void draw();

@Override

protected Object clone(){

Object clone=null;

try {

clone=super.clone();

System.out.println("cloned");

} catch (CloneNotSupportedException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

return clone;

}

}

2)实体类创建

public class Circle extends Shape{

public Circle() {

type="circle";

}

@Override

void draw() {

System.out.println("Circle draw()");

}

}

public class Rectangle extends Shape {

public Rectangle() {

type="rectangle";

}

@Override

void draw() {

System.out.println("Rectangle draw()");

}

}

3)获取实体的克隆类

public class ShapeCache {

private static Hashtable shapeMap=new Hashtable();

public static Shape getShape(String shapeId){

Shape cacheShape=shapeMap.get(shapeId);

return (Shape) cacheShape.clone();

}

//添加形状

public static void loadCache(){

Circle circle=new Circle();

circle.setId("1");

shapeMap.put(circle.getId(), circle);

Rectangle rectangle=new Rectangle();

rectangle.setId("2");

shapeMap.put(rectangle.getId(), rectangle);

}

}

4)测试类

public class PrototypeTest {

public static void main(String[] args) {

ShapeCache.loadCache();

Shape cloneShape,cloneShape1;

for(int i=0;i<3;i++){

cloneShape=ShapeCache.getShape("1");

System.out.println("Shape 1 :"+cloneShape.getType());

cloneShape.draw();

cloneShape1=ShapeCache.getShape("2");

System.out.println("Shape 2 :"+cloneShape1.getType());

cloneShape1.draw();

}

}

}

5)后台运行

cloned

Shape 1 :circle

Circle draw()

cloned

Shape 2 :rectangle

Rectangle draw()

cloned

Shape 1 :circle

Circle draw()

cloned

Shape 2 :rectangle

Rectangle draw()

cloned

Shape 1 :circle

Circle draw()

cloned

Shape 2 :rectangle

Rectangle draw()

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值