Advertisement
rafibatam

Design Pattern Prototype JAVA

Mar 21st, 2019
123
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.51 KB | None | 0 0
  1. Prototype Pattern adalah sebuah pattern yang mengacu pada pembuatan "duplicate object" atau bisa dikatakan pattern ini membuat object dengan menduplikat object yang telah ada. Pattern ini fungsinya untuk memangkas cost dalam pembuatan object baru, artinya tanpa mendeklarasikan keyword "new" yang menyebabkan pemborosan memory dalam program. Prototype pattern ini termasuk ke dalam Creational Pattern.
  2.  
  3. class Key implements Cloneable {
  4.     private String typeKey;
  5.    
  6.     public Key(String type) {
  7.         setKey(type);
  8.     }
  9.    
  10.     public Object clone() {
  11.         Key example = null;
  12.         try {
  13.             example = (Key) super.clone();
  14.         }
  15.        
  16.         catch(Exception e) {
  17.            
  18.         }
  19.        
  20.         return example;
  21.     }
  22.    
  23.     public String getKey() {
  24.         return typeKey;
  25.     }
  26.    
  27.     public void setKey(String typeKey) {
  28.         this.typeKey = typeKey;
  29.     }
  30. }
  31.  
  32. public class Progress {
  33.     public static void main(String[] args) {
  34.         Key car = new Key("Toyota");
  35.         Key motorCycle = new Key("Honda");
  36.        
  37.         System.out.println("Kunci yang akan di duplikat :");
  38.         System.out.println("1. Kunci mobil merk " + car.getKey());
  39.         System.out.println("2. Kunci motor merk " + motorCycle.getKey());
  40.        
  41.         System.out.println("\n1.Kunci mobil di duplikat");
  42.         Key carDuplicate = (Key) car.clone();
  43.         System.out.println("Kunci mobil merk " + carDuplicate.getKey() + " berhasil di duplikat");
  44.        
  45.         System.out.println("\n2. Kunci motor di duplikat");
  46.         Key motorDuplicate = (Key) motorCycle.clone();
  47.         System.out.println("Kunci mobil merk " + motorDuplicate.getKey() + " berhasil di duplikat");
  48.     }
  49. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement