原型模式主要用于对象的复制,它的核心是就是类图中的原型类Prototype。Prototype类需要具备以下两个条件:
原型模式的优点及适用场景
使用原型模式创建对象比直接new一个对象在性能上要好的多,因为Object类的clone方法是一个本地方法,它直接操作内存中的二进制流,特别是复制大对象时,性能的差别非常明显。
使用原型模式的另一个好处是简化对象的创建,使得创建对象就像我们在编辑文档时的复制粘贴一样简单。
因为以上优点,所以在需要重复地创建相似对象时可以考虑使用原型模式。比如需要在一个循环体内创建对象,假如对象创建过程比较复杂或者循环次数很多的话,使用原型模式不但可以简化创建过程,而且可以使系统的整体性能提高很多。
package mode.prototype;
/**
*
* 实现一个抽象的家具类,用来定义一些子类必须有的方法
*
* */
public abstract class AbstractFurniture implements Cloneable {
public abstract void draw();
@Override
protected Object clone() throws CloneNotSupportedException {
// TODO Auto-generated method stub
return super.clone();
}
}
package mode.prototype;
import java.awt.Point;
/**
*
* 一个圆形桌子的实例
*
* */
public class CircleTable extends AbstractFurniture {
protected Point center;
public Point getCenter() {
return center;
}
public void setCenter(Point center) {
this.center = center;
}
@Override
protected Object clone() throws CloneNotSupportedException {
Object o = super.clone();
if (this.center != null) {
((CircleTable) o).center = (Point) center.clone();
}
return o;
}
@Override
public void draw() {
System.out.println("\t圆桌\t中心:(" + center.getX() + ", " + center.getY()
+ ")");
}
}
package mode.prototype;
import java.util.Enumeration;
import java.util.Vector;
/**
*
* 实现一个房子对象,房子中放着很多很多的圆形桌子
*
* */
public class House {
private Vector<AbstractFurniture> vector;
public House() {
vector = new Vector<AbstractFurniture>();
}
public void addFurniture(AbstractFurniture furniture) {
vector.addElement(furniture);
System.out.println("现有家具.....");
Enumeration<AbstractFurniture> enumeration = vector.elements();
while (enumeration.hasMoreElements()) {
AbstractFurniture f = (AbstractFurniture) enumeration.nextElement();
f.draw();
}
System.out.println();
}
}
package mode.prototype;
import java.awt.Point;
/**
* @ClassName: Application
* @Description: 我们的应用程序,用来给房子中放入圆形的桌子
* @author mpc
* @date 2014年12月30日 下午1:46:07
*
*/
public class Application {
private AbstractFurniture circleTablePrototype;
public AbstractFurniture getCircleTablePrototype() {
return circleTablePrototype;
}
public void setCircleTablePrototype(AbstractFurniture circleTablePrototype) {
this.circleTablePrototype = circleTablePrototype;
}
public void runAppExample() throws Exception {
House house = new House();
CircleTable circleTable = null;
// 从工剧烈选择一个家具加入到房子中
circleTable = (CircleTable) circleTablePrototype.clone();
circleTable.setCenter(new Point(10, 10));
house.addFurniture(circleTable);
// 从工具列选择一个家具加入房子中
circleTable = (CircleTable) circleTablePrototype.clone();
circleTable.setCenter(new Point(20, 30));
house.addFurniture(circleTable);
}
public static void main(String[] args) throws Exception {
Application application = new Application();
application.setCircleTablePrototype(new CircleTable());
application.runAppExample();
}
}
原文地址:http://blog.csdn.net/u012613903/article/details/44256723