Prototype Design Pattern

Before we proceed to Prototype Design Pattern, We need to review on Clone() method in Java.

The Object cloning is a way to create exact copy of an object. The clone() method of Object class is used to clone an object.

The java.lang.Cloneable interface must be implemented by the class whose object clone we want to create. If we don‘t implement Cloneable interface, clone method

generates CloneNotSupportedException.

The clone() method is defined in the Object Class.

Advantage of Clone() method.

The clone() method saves the extra processing task for creating the exact copy of an object. If we perform by using the new keyword, it will take a lot of

processing time to be performed that is why we use object cloning.

Clone() is the fastest way to copy array.

Disadvantages of Clone()

Disadvantage of Object cloning

Following is a list of some disadvantages of clone() method:

  • To use the Object.clone() method, we have to change a lot of syntaxes to our code, like implementing a Cloneable interface, defining the clone() method and handling CloneNotSupportedException, and finally, calling Object.clone() etc.
  • We have to implement cloneable interface while it doesn‘t have any methods in it. We just have to use it to tell the JVM that we can perform clone() on our object.
  • Object.clone() is protected, so we have to provide our own clone() and indirectly call Object.clone() from it.
  • Object.clone() doesn‘t invoke any constructor so we don‘t have any control over object construction.
  • If you want to write a clone method in a child class then all of its superclasses should define the clone() method in them or inherit it from another parent class. Otherwise, the super.clone() chain will fail.
  • Object.clone() supports only shallow copying but we will need to override it if we need deep cloning.
class Student18 implements Cloneable{
2.int rollno;
3.String name;
4.
5.Student18(int rollno,String name){
6.this.rollno=rollno;
7.this.name=name;
8.}
9.
10.public Object clone()throws CloneNotSupportedException{
11.return super.clone();
12.}
13.
14.public static void main(String args[]){
15.try{
16.Student18 s1=new Student18(101,"amit");
17.
18.Student18 s2=(Student18)s1.clone();
19.
20.System.out.println(s1.rollno+" "+s1.name);
21.System.out.println(s2.rollno+" "+s2.name);
22.
23.}catch(CloneNotSupportedException c){}
24.
25.}
26.}  

Prototype Design Pattern.

Prototype pattern refers to creating duplicate object while keeping performance in mind.

This type of design pattern comes under creational pattern.

This pattern is used when creation of object directly is costly. For example, an object is to be created after a costly database operation. We can cache the object, returns its clone on next request and update the database as and when needed thus reducing database calls.

Below is an example of Prototype design pattern demo with diagram flow and Code.

Step 1. Create an abstract class implementing Clonable interface.

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;
   }
}

Create Concrete Classes extending the above class.

1. Rectangle.java

public class Rectangle extends Shape {

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

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

2. Square.java

public class Square extends Shape {

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

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

3. Circle.java

public class Circle extends Shape {

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

   @Override
   public void draw() {
      System.out.println("Inside Circle::draw() method.");
   }
}

Step 3. Create a class to get concrete classes from database and store them in a Hashtable.

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();
   }

   // for each shape run database query and create shape
   // shapeMap.put(shapeKey, shape);
   // for example, we are adding three shapes

   public static void loadCache() {
      Circle circle = new Circle();
      circle.setId("1");
      shapeMap.put(circle.getId(),circle);

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

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

Step 4. PrototypePatternDemo uses ShapeCache class to get clones of shapes stored in a Hashtable.

PrototypePatternDemo.java

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

      Shape clonedShape = (Shape) ShapeCache.getShape("1");
      System.out.println("Shape : " + clonedShape.getType());        

      Shape clonedShape2 = (Shape) ShapeCache.getShape("2");
      System.out.println("Shape : " + clonedShape2.getType());        

      Shape clonedShape3 = (Shape) ShapeCache.getShape("3");
      System.out.println("Shape : " + clonedShape3.getType());
   }
}

原文地址:https://www.cnblogs.com/codingyangmao/p/11263293.html

时间: 2024-11-07 01:31:48

Prototype Design Pattern的相关文章

Design Pattern Prototype 原型设计模式

Prototype设计模式其实就是利用一个深拷贝的功能,在原有的类中,通过一个clone函数,创建一个新的类,并可以利用好原有的数据. 这样可以轻易clone出多个新的对象操作,而且都有各自的内存空间. #include <string> #include <iostream> using namespace std; class MultiData { protected: bool b; char c; string s; int a; public: virtual Mult

C++ Design Pattern: What is a Design Pattern?

Q: What is a Design Pattern? A: Design Patterns represent solutions to problems what arise when developing software within a particular context. Each pattern describes a problem which occurs over and over again in our environment, and then describes

golang and design pattern

学习java的时候,“设计模式”这个概念到处可见.比如java.io里面的 decorated pattern,Object.Clone(Object)原生态支持Prototype pattern,Swing事件响应的Observer pattern, io.util和Event中的Adapter pattern.还有第三方框架中形形色色的design pattern.有时候从代码中突然发现一个design pattern,喜不自禁. 现在学习go语言,就再也没有从go语言中听到design p

设计模式(Design pattern)概述

设计模式(Design pattern)是一套被反复使用.多数人知晓的.经过分类编目的.代码设计经验的总结, 使用设计模式是为了可重用代码.让代码更容易被他人理解.保证代码可靠性 设计框架 可复用面向对象软件系统一般划分为两大类:应用程序工具箱和框架(Framework) 我们平时开发的具体软件都是应用程序 而框架是构成一类特定软件可复用设计的一组相互协作的类 框架通常定义了应用体系的整体结构类和对象的关系等等设计参数,以便于具体应用实现者能集中精力于应用本身的特定细节. 框架主要记录软件应用中

DP什么意思 design pattern 设计模式

DP  design pattern 大话设计模式  中的DP 是设计模式的意思 设计模式的书 ,最经典最原始的就是 GOF 的<设计模式>了. 设计模式的书基本上大多是以这 20 多个模式分开讲.含<大话设计模式> 学了 OOL 写的程序基本上是 OB 的. 只有慢慢掌握了 DP 才能写出真正的 OO 程序. 思想 -> 设计原则 -> DP -> OOD

Head First Design Pattern 读书笔记(2) 观察者模式

Head First Design Pattern 读书笔记(2) Observer Pattern 观察者模式 Observer Pattern 类图 定义 观察者模式:在对象间定义一个一对多的关系,当其中一个的对象发生改变时,所有依赖于这个对象的对象(即观察者们)都会自动更新或做执行某些行为. 几个OO的原测 尽量以松耦合的方式处理对象间关系–>软件工程时候学的"高內聚,低耦合"的好处 关于观察者模式 被观察对象通知观察者可以使用推送的方式(类图中带参数的notifyActi

Design Pattern Singleton 单一模式

单一模式的几个注意点: 一) 设计单一模式,首先需要把构造函数给私有化了,不让外界访问,那么外界只能通过提供的函数获取一个新的类. 二) C++的单一模式,记得要在类外初始化一个类,否则或内存出错的. 三) 这个唯一的类必须是要静态的 程序: #ifndef _SINGLETON_H #define _SINGLETON_H #include <iostream> #include <string> using namespace std; class DuGuJiuJian {

Design Pattern 设计模式1 - Strategy 1

实现 : Defferent Heros attack Defferently. - 不同的英雄使用不用的招数 Strategy设计的思路: 基类A,更加小的基类B,新的继承类C: 1 从基类A中抽出一个更加小的基类B 2 利用这个更加小的基类B实现不同的效果 3 把这个更加小的基类B包含进基类A中去 4 新的继承类C只需要和基类A打交道,设计不同行为,不需要理会更加小的基类B #pragma once #ifndef _STRATEGY_HEROS_H #define _STRATEGY_HE

简单工厂设计模式(Simple Factory Design Pattern)

[引言]最近在Youtub上面看到一个讲解.net设计模式的视频,其中作者的一个理解让我印象很深刻:所谓的设计模式其实就是运用面向对象编程的思想来解决平时代码中的紧耦合,低扩展的问题.另外一点比较有见解的是,区分了设计模式(Design Pattern),结构模式(Architecture Pattern),架构类型(Architecture Style). 如下图所示 Design Pattern:是基于代码层面的,就是针对解决功能模块之间的问题而采用恰当的设计模式,比如依赖注入,简单工厂,适