SlideShare a Scribd company logo
Prototype Design Pattern
• It is a type of Creational Design Pattern.
• It is used when you want to avoid multiple
object creation of same instance, instead you
copy the object to new object and then we can
modify.
• Object which we are copying should provide
copying feature by implementing cloneable
interface.
• We can override clone() method to implement
as per our need.
Let us create first demo.java with main function.
package com.prototype;
public class Demo {
public static void main(String[] args){
}
}
Now let us create the Book class where the book id and book name will be printed.
package com.prototype;
public class Book
{
private int bid;
private String bname;
public int getBid() {
return bid;
}
public void setBid(int bid) {
this.bid = bid;
}
public String getBname() {
return bname;
}
public void setBname(String bname) {
this.bname = bname;
}
@Override
public String toString() {
return "Book [bid=" + bid + ", bname=" + bname + "]";
}
}
Now let us consider all the Books will be stored in one BookShop, hence we are going to create a BookShop class.
package com.prototype;
import java.util.ArrayList;
import java.util.List;
public class BookShop
{
private String shopName;
List<Book> books = new ArrayList<>();
public String getShopName() {
return shopName;
}
public void setShopName(String shopName) {
this.shopName = shopName;
}
public List<Book> getBooks() {
return books;
}
public void setBooks(List<Book> books) {
this.books = books;
}
@Override
public String toString() {
return "BookShop [shopName=" + shopName + ", books=" + books + "]";
}
}
Now let us go to demo.java again.
package com.prototype;
public class Demo {
public static void main(String[] args){
BookShop bs = new BookShop(); //try to create object bs
System.out.println(bs); // print will return null values
}
}
Will return an output like this because we have not specified any values in BookShop.
So create a method in BookShop which will add data to the BookShop.
So let us come in BookShop again.
package com.prototype;
import java.util.ArrayList;
import java.util.List;
public class BookShop
{
private String shopName;
List<Book> books = new ArrayList<>();
public String getShopName() {
return shopName;
}
public void setShopName(String shopName) {
this.shopName = shopName;
}
public List<Book> getBooks() {
return books;
}
public void setBooks(List<Book> books) {
this.books = books;
}
public void loadData(){
for(int i=1; i<=10; i++){
Book b = new Book();
b.setBid(i);
b.setBname("Books "+i);
getBooks().add(b);
}
}
@Override
public String toString() {
return "BookShop [shopName=" + shopName + ", books=" + books + "]";
}
}
Then go to Demo again and add bookname and try to load the data from the DB.
package com.prototype;
public class Demo {
public static void main(String[] args){
BookShop bs = new BookShop(); //try to create object bs
bs.setShopName("Shop1");
bs.loadData();
System.out.println(bs);
}
}
Will return an output like this after loading the data from BookShop. (ShopName is modified…)
Up to this, there is no Prototype Design Pattern.
So lets do the following in Demo.java again...
package com.prototype;
public class Demo {
public static void main(String[] args){
BookShop bs = new BookShop(); //try to create object bs
bs.setShopName("Shop1");
bs.loadData();
System.out.println(bs);
BookShop bs1 = new BookShop(); //try to create object bs
bs1.setShopName("Shop2");
bs1.loadData();
System.out.println(bs1);
}
}
• So the second object is loading the same data from the database again.
• But if it is required to create different object to access the same data then second
object also can try to copy or clone the same from the first object.
• That is the concept of Protype Design Method.
So lets do the following in Demo.java again...
package com.prototype;
public class Demo {
public static void main(String[] args){
BookShop bs = new BookShop(); //try to create object bs
bs.setShopName("Shop1");
bs.loadData();
System.out.println(bs);
BookShop bs1 = bs.clone(); //instead of creating new object create clone
bs1.setShopName("Shop2");
bs1.loadData();
System.out.println(bs1);
}
}
‘Clone’ method is in the object class. However as it is protected there so to use that it requires to set the permission.
So let us come in BookShop again.
package com.prototype;
import java.util.ArrayList;
import java.util.List;
public class BookShop implements Cloneable
{
private String shopName;
List<Book> books = new ArrayList<>();
public String getShopName() {
return shopName;
}
public void setShopName(String shopName) {
this.shopName = shopName;
}
public List<Book> getBooks() {
return books;
}
public void setBooks(List<Book> books) {
this.books = books;
}
public void loadData(){
for(int i=1; i<=10; i++){
Book b = new Book();
b.setBid(i);
b.setBname("Books "+i);
getBooks().add(b);
}
}
@Override
public String toString() {
return "BookShop [shopName=" + shopName + ", books=" + books + "]";
}
///////////////////////////////////////////////////////////////////////////////// next slide
}
• //to achieve cloning we have to override a clone method
@Override
protected Object clone() throws CloneNotSupportedException {
// TODO Auto-generated method stub
return super.clone();
}
And in Demo.java the following:
BookShop bs1 = (BookShop) bs.clone();
And
public static void main(String[] args) throws CloneNotSupportedException
Just like...
package com.prototype;
public class Demo {
public static void main(String[] args) throws CloneNotSupportedException
{
BookShop bs = new BookShop();
bs.setShopName("Shop1");
bs.loadData();
System.out.println(bs);
BookShop bs1 = (BookShop)bs.clone();
bs1.setShopName("Shop2");
System.out.println(bs1);
}
}
But one problem...
package com.prototype;
public class Demo {
public static void main(String[] args) throws CloneNotSupportedException
{
BookShop bs = new BookShop();
bs.setShopName("Shop1");
bs.loadData();
bs.getBooks().remove(2);
System.out.println(bs);
BookShop bs1 = (BookShop)bs.clone();
bs1.setShopName("Shop2");
System.out.println(bs1);
}
}
• So results deleting from both bs and bs1.
• Instead of creating two separate object, by cloning we are getting two references
of a single object.
• Thus this kind of cloning is not creating too much impact.
• So how to achieve ‘Deep Cloning’…
• Go to ‘BookShop.java’ and do the following…
So let us come in BookShop again.
package com.prototype;
import java.util.ArrayList;
import java.util.List;
public class BookShop implements Cloneable
{
private String shopName;
List<Book> books = new ArrayList<>();
public String getShopName() {
return shopName;
}
public void setShopName(String shopName) {
this.shopName = shopName;
}
public List<Book> getBooks() {
return books;
}
public void setBooks(List<Book> books) {
this.books = books;
}
public void loadData(){
for(int i=1; i<=10; i++){
Book b = new Book();
b.setBid(i);
b.setBname("Books "+i);
getBooks().add(b);
}
}
@Override
public String toString() {
return "BookShop [shopName=" + shopName + ", books=" + books + "]";
}
///////////////////////////////////////////////////////////////////////////////// next slide
}
@Override
protected BookShop clone() throws CloneNotSupportedException {
// TODO Auto-generated method stub
return super.clone();
}
// And in Demo.java, in case of deepcloning in Bookshop, when you are returning bookshop
and not using object then you dont need to cast bookshop :
BookShop bs1 = bs.clone();
And remove the return super.clone() also, like the following:
protected BookShop clone() throws CloneNotSupportedException {
// TODO Auto-generated method stub
//return super.clone();
BookShop shop = new BookShop();
for(Book b : this.getBooks()) // Don’t put these three rows first and with return only
{ // no data will be shown in output for the second object as nothing is returned
shop.getBooks().add(b);
}
return shop;
}
Now finally go to Demo.java and complete it...
package com.prototype;
public class Demo {
public static void main(String[] args) throws CloneNotSupportedException
{
BookShop bs = new BookShop();
bs.setShopName("Shop1");
bs.loadData();
BookShop bs1 = bs.clone();
bs.getBooks().remove(2);
bs1.setShopName("Shop2");
System.out.println(bs);
System.out.println(bs1);
}
}

More Related Content

Similar to 03 - Prototype Design Pattern - Slideshare.pptx

A single language for backend and frontend from AngularJS to cloud with Clau...
A single language for backend and frontend  from AngularJS to cloud with Clau...A single language for backend and frontend  from AngularJS to cloud with Clau...
A single language for backend and frontend from AngularJS to cloud with Clau...
Corley S.r.l.
 
A single language for backend and frontend from AngularJS to cloud with Clau...
A single language for backend and frontend  from AngularJS to cloud with Clau...A single language for backend and frontend  from AngularJS to cloud with Clau...
A single language for backend and frontend from AngularJS to cloud with Clau...
Walter Dal Mut
 
Firebase for Apple Developers - SwiftHeroes
Firebase for Apple Developers - SwiftHeroesFirebase for Apple Developers - SwiftHeroes
Firebase for Apple Developers - SwiftHeroes
Peter Friese
 
Building .NET-based Applications with C#
Building .NET-based Applications with C#Building .NET-based Applications with C#
Building .NET-based Applications with C#
Umar Farooq
 
Week 9 IUB c#
Week 9 IUB c#Week 9 IUB c#
Week 9 IUB c#
Umar Farooq
 
OO in JavaScript
OO in JavaScriptOO in JavaScript
OO in JavaScript
Gunjan Kumar
 
813 LAB Library book sorting Note that only maincpp can .pdf
813 LAB Library book sorting Note that only maincpp can .pdf813 LAB Library book sorting Note that only maincpp can .pdf
813 LAB Library book sorting Note that only maincpp can .pdf
sastaindin
 
properties-how-do-i - Transcript.pdf
properties-how-do-i - Transcript.pdfproperties-how-do-i - Transcript.pdf
properties-how-do-i - Transcript.pdf
ShaiAlmog1
 
Let's JavaScript
Let's JavaScriptLet's JavaScript
Let's JavaScript
Paweł Dorofiejczyk
 
Stack Implementation
Stack ImplementationStack Implementation
Stack Implementation
Zidny Nafan
 
Scalable JavaScript Design Patterns
Scalable JavaScript Design PatternsScalable JavaScript Design Patterns
Scalable JavaScript Design Patterns
Addy Osmani
 
Java-Module 3-PPT-TPS.pdf.Java-Module 3-PPT-TPS.pdf
Java-Module 3-PPT-TPS.pdf.Java-Module 3-PPT-TPS.pdfJava-Module 3-PPT-TPS.pdf.Java-Module 3-PPT-TPS.pdf
Java-Module 3-PPT-TPS.pdf.Java-Module 3-PPT-TPS.pdf
kakarthik685
 
JavaScript Workshop
JavaScript WorkshopJavaScript Workshop
JavaScript Workshop
Pamela Fox
 
Chapter ii(oop)
Chapter ii(oop)Chapter ii(oop)
Chapter ii(oop)
Chhom Karath
 
Firebase for Apple Developers
Firebase for Apple DevelopersFirebase for Apple Developers
Firebase for Apple Developers
Peter Friese
 
Link.javaLink.javapackage com.bookstore.domain.model;import .docx
Link.javaLink.javapackage com.bookstore.domain.model;import .docxLink.javaLink.javapackage com.bookstore.domain.model;import .docx
Link.javaLink.javapackage com.bookstore.domain.model;import .docx
SHIVA101531
 
constructors.pptx
constructors.pptxconstructors.pptx
constructors.pptx
Epsiba1
 
JS Level Up: Prototypes
JS Level Up: PrototypesJS Level Up: Prototypes
JS Level Up: Prototypes
Vernon Kesner
 

Similar to 03 - Prototype Design Pattern - Slideshare.pptx (20)

A single language for backend and frontend from AngularJS to cloud with Clau...
A single language for backend and frontend  from AngularJS to cloud with Clau...A single language for backend and frontend  from AngularJS to cloud with Clau...
A single language for backend and frontend from AngularJS to cloud with Clau...
 
A single language for backend and frontend from AngularJS to cloud with Clau...
A single language for backend and frontend  from AngularJS to cloud with Clau...A single language for backend and frontend  from AngularJS to cloud with Clau...
A single language for backend and frontend from AngularJS to cloud with Clau...
 
Firebase for Apple Developers - SwiftHeroes
Firebase for Apple Developers - SwiftHeroesFirebase for Apple Developers - SwiftHeroes
Firebase for Apple Developers - SwiftHeroes
 
Building .NET-based Applications with C#
Building .NET-based Applications with C#Building .NET-based Applications with C#
Building .NET-based Applications with C#
 
Week 9 IUB c#
Week 9 IUB c#Week 9 IUB c#
Week 9 IUB c#
 
OO in JavaScript
OO in JavaScriptOO in JavaScript
OO in JavaScript
 
813 LAB Library book sorting Note that only maincpp can .pdf
813 LAB Library book sorting Note that only maincpp can .pdf813 LAB Library book sorting Note that only maincpp can .pdf
813 LAB Library book sorting Note that only maincpp can .pdf
 
Thread
ThreadThread
Thread
 
properties-how-do-i - Transcript.pdf
properties-how-do-i - Transcript.pdfproperties-how-do-i - Transcript.pdf
properties-how-do-i - Transcript.pdf
 
Let's JavaScript
Let's JavaScriptLet's JavaScript
Let's JavaScript
 
Stack Implementation
Stack ImplementationStack Implementation
Stack Implementation
 
Scalable JavaScript Design Patterns
Scalable JavaScript Design PatternsScalable JavaScript Design Patterns
Scalable JavaScript Design Patterns
 
Java-Module 3-PPT-TPS.pdf.Java-Module 3-PPT-TPS.pdf
Java-Module 3-PPT-TPS.pdf.Java-Module 3-PPT-TPS.pdfJava-Module 3-PPT-TPS.pdf.Java-Module 3-PPT-TPS.pdf
Java-Module 3-PPT-TPS.pdf.Java-Module 3-PPT-TPS.pdf
 
JavaScript Workshop
JavaScript WorkshopJavaScript Workshop
JavaScript Workshop
 
Chapter ii(oop)
Chapter ii(oop)Chapter ii(oop)
Chapter ii(oop)
 
Firebase for Apple Developers
Firebase for Apple DevelopersFirebase for Apple Developers
Firebase for Apple Developers
 
LectureNotes-06-DSA
LectureNotes-06-DSALectureNotes-06-DSA
LectureNotes-06-DSA
 
Link.javaLink.javapackage com.bookstore.domain.model;import .docx
Link.javaLink.javapackage com.bookstore.domain.model;import .docxLink.javaLink.javapackage com.bookstore.domain.model;import .docx
Link.javaLink.javapackage com.bookstore.domain.model;import .docx
 
constructors.pptx
constructors.pptxconstructors.pptx
constructors.pptx
 
JS Level Up: Prototypes
JS Level Up: PrototypesJS Level Up: Prototypes
JS Level Up: Prototypes
 

Recently uploaded

TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
EugeneSaldivar
 
The approach at University of Liverpool.pptx
The approach at University of Liverpool.pptxThe approach at University of Liverpool.pptx
The approach at University of Liverpool.pptx
Jisc
 
Digital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and ResearchDigital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and Research
Vikramjit Singh
 
Guidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th SemesterGuidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th Semester
Atul Kumar Singh
 
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
Levi Shapiro
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
Jisc
 
The French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free downloadThe French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free download
Vivekanand Anglo Vedic Academy
 
The Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptxThe Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptx
DhatriParmar
 
Best Digital Marketing Institute In NOIDA
Best Digital Marketing Institute In NOIDABest Digital Marketing Institute In NOIDA
Best Digital Marketing Institute In NOIDA
deeptiverma2406
 
CACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdfCACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdf
camakaiclarkmusic
 
STRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBC
STRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBCSTRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBC
STRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBC
kimdan468
 
Honest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptxHonest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptx
timhan337
 
"Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe..."Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe...
SACHIN R KONDAGURI
 
2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...
Sandy Millin
 
How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17
Celine George
 
Marketing internship report file for MBA
Marketing internship report file for MBAMarketing internship report file for MBA
Marketing internship report file for MBA
gb193092
 
Francesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptxFrancesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptx
EduSkills OECD
 
special B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdfspecial B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdf
Special education needs
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
siemaillard
 
Lapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdfLapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdf
Jean Carlos Nunes Paixão
 

Recently uploaded (20)

TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
 
The approach at University of Liverpool.pptx
The approach at University of Liverpool.pptxThe approach at University of Liverpool.pptx
The approach at University of Liverpool.pptx
 
Digital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and ResearchDigital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and Research
 
Guidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th SemesterGuidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th Semester
 
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
 
The French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free downloadThe French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free download
 
The Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptxThe Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptx
 
Best Digital Marketing Institute In NOIDA
Best Digital Marketing Institute In NOIDABest Digital Marketing Institute In NOIDA
Best Digital Marketing Institute In NOIDA
 
CACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdfCACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdf
 
STRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBC
STRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBCSTRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBC
STRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBC
 
Honest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptxHonest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptx
 
"Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe..."Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe...
 
2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...
 
How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17
 
Marketing internship report file for MBA
Marketing internship report file for MBAMarketing internship report file for MBA
Marketing internship report file for MBA
 
Francesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptxFrancesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptx
 
special B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdfspecial B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdf
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
 
Lapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdfLapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdf
 

03 - Prototype Design Pattern - Slideshare.pptx

  • 2. • It is a type of Creational Design Pattern. • It is used when you want to avoid multiple object creation of same instance, instead you copy the object to new object and then we can modify. • Object which we are copying should provide copying feature by implementing cloneable interface. • We can override clone() method to implement as per our need.
  • 3. Let us create first demo.java with main function. package com.prototype; public class Demo { public static void main(String[] args){ } }
  • 4. Now let us create the Book class where the book id and book name will be printed. package com.prototype; public class Book { private int bid; private String bname; public int getBid() { return bid; } public void setBid(int bid) { this.bid = bid; } public String getBname() { return bname; } public void setBname(String bname) { this.bname = bname; } @Override public String toString() { return "Book [bid=" + bid + ", bname=" + bname + "]"; } }
  • 5. Now let us consider all the Books will be stored in one BookShop, hence we are going to create a BookShop class. package com.prototype; import java.util.ArrayList; import java.util.List; public class BookShop { private String shopName; List<Book> books = new ArrayList<>(); public String getShopName() { return shopName; } public void setShopName(String shopName) { this.shopName = shopName; } public List<Book> getBooks() { return books; } public void setBooks(List<Book> books) { this.books = books; } @Override public String toString() { return "BookShop [shopName=" + shopName + ", books=" + books + "]"; } }
  • 6. Now let us go to demo.java again. package com.prototype; public class Demo { public static void main(String[] args){ BookShop bs = new BookShop(); //try to create object bs System.out.println(bs); // print will return null values } } Will return an output like this because we have not specified any values in BookShop. So create a method in BookShop which will add data to the BookShop.
  • 7. So let us come in BookShop again. package com.prototype; import java.util.ArrayList; import java.util.List; public class BookShop { private String shopName; List<Book> books = new ArrayList<>(); public String getShopName() { return shopName; } public void setShopName(String shopName) { this.shopName = shopName; } public List<Book> getBooks() { return books; } public void setBooks(List<Book> books) { this.books = books; } public void loadData(){ for(int i=1; i<=10; i++){ Book b = new Book(); b.setBid(i); b.setBname("Books "+i); getBooks().add(b); } } @Override public String toString() { return "BookShop [shopName=" + shopName + ", books=" + books + "]"; } }
  • 8. Then go to Demo again and add bookname and try to load the data from the DB. package com.prototype; public class Demo { public static void main(String[] args){ BookShop bs = new BookShop(); //try to create object bs bs.setShopName("Shop1"); bs.loadData(); System.out.println(bs); } } Will return an output like this after loading the data from BookShop. (ShopName is modified…) Up to this, there is no Prototype Design Pattern.
  • 9. So lets do the following in Demo.java again... package com.prototype; public class Demo { public static void main(String[] args){ BookShop bs = new BookShop(); //try to create object bs bs.setShopName("Shop1"); bs.loadData(); System.out.println(bs); BookShop bs1 = new BookShop(); //try to create object bs bs1.setShopName("Shop2"); bs1.loadData(); System.out.println(bs1); } }
  • 10. • So the second object is loading the same data from the database again. • But if it is required to create different object to access the same data then second object also can try to copy or clone the same from the first object. • That is the concept of Protype Design Method.
  • 11. So lets do the following in Demo.java again... package com.prototype; public class Demo { public static void main(String[] args){ BookShop bs = new BookShop(); //try to create object bs bs.setShopName("Shop1"); bs.loadData(); System.out.println(bs); BookShop bs1 = bs.clone(); //instead of creating new object create clone bs1.setShopName("Shop2"); bs1.loadData(); System.out.println(bs1); } } ‘Clone’ method is in the object class. However as it is protected there so to use that it requires to set the permission.
  • 12. So let us come in BookShop again. package com.prototype; import java.util.ArrayList; import java.util.List; public class BookShop implements Cloneable { private String shopName; List<Book> books = new ArrayList<>(); public String getShopName() { return shopName; } public void setShopName(String shopName) { this.shopName = shopName; } public List<Book> getBooks() { return books; } public void setBooks(List<Book> books) { this.books = books; } public void loadData(){ for(int i=1; i<=10; i++){ Book b = new Book(); b.setBid(i); b.setBname("Books "+i); getBooks().add(b); } } @Override public String toString() { return "BookShop [shopName=" + shopName + ", books=" + books + "]"; } ///////////////////////////////////////////////////////////////////////////////// next slide }
  • 13. • //to achieve cloning we have to override a clone method @Override protected Object clone() throws CloneNotSupportedException { // TODO Auto-generated method stub return super.clone(); } And in Demo.java the following: BookShop bs1 = (BookShop) bs.clone(); And public static void main(String[] args) throws CloneNotSupportedException
  • 14. Just like... package com.prototype; public class Demo { public static void main(String[] args) throws CloneNotSupportedException { BookShop bs = new BookShop(); bs.setShopName("Shop1"); bs.loadData(); System.out.println(bs); BookShop bs1 = (BookShop)bs.clone(); bs1.setShopName("Shop2"); System.out.println(bs1); } }
  • 15. But one problem... package com.prototype; public class Demo { public static void main(String[] args) throws CloneNotSupportedException { BookShop bs = new BookShop(); bs.setShopName("Shop1"); bs.loadData(); bs.getBooks().remove(2); System.out.println(bs); BookShop bs1 = (BookShop)bs.clone(); bs1.setShopName("Shop2"); System.out.println(bs1); } }
  • 16. • So results deleting from both bs and bs1. • Instead of creating two separate object, by cloning we are getting two references of a single object. • Thus this kind of cloning is not creating too much impact. • So how to achieve ‘Deep Cloning’… • Go to ‘BookShop.java’ and do the following…
  • 17. So let us come in BookShop again. package com.prototype; import java.util.ArrayList; import java.util.List; public class BookShop implements Cloneable { private String shopName; List<Book> books = new ArrayList<>(); public String getShopName() { return shopName; } public void setShopName(String shopName) { this.shopName = shopName; } public List<Book> getBooks() { return books; } public void setBooks(List<Book> books) { this.books = books; } public void loadData(){ for(int i=1; i<=10; i++){ Book b = new Book(); b.setBid(i); b.setBname("Books "+i); getBooks().add(b); } } @Override public String toString() { return "BookShop [shopName=" + shopName + ", books=" + books + "]"; } ///////////////////////////////////////////////////////////////////////////////// next slide }
  • 18. @Override protected BookShop clone() throws CloneNotSupportedException { // TODO Auto-generated method stub return super.clone(); } // And in Demo.java, in case of deepcloning in Bookshop, when you are returning bookshop and not using object then you dont need to cast bookshop : BookShop bs1 = bs.clone(); And remove the return super.clone() also, like the following: protected BookShop clone() throws CloneNotSupportedException { // TODO Auto-generated method stub //return super.clone(); BookShop shop = new BookShop(); for(Book b : this.getBooks()) // Don’t put these three rows first and with return only { // no data will be shown in output for the second object as nothing is returned shop.getBooks().add(b); } return shop; }
  • 19. Now finally go to Demo.java and complete it... package com.prototype; public class Demo { public static void main(String[] args) throws CloneNotSupportedException { BookShop bs = new BookShop(); bs.setShopName("Shop1"); bs.loadData(); BookShop bs1 = bs.clone(); bs.getBooks().remove(2); bs1.setShopName("Shop2"); System.out.println(bs); System.out.println(bs1); } }