[Design Pattern] Erzeugende Muster: Prototype


#1
Hallo,

dieser Beitrag erklärt das erzeugende Muster: Prototype

Java:
package de.tutorials.design.patterns.creational;

import org.jpatterns.gof.PrototypePattern.Prototype;

public class PrototypePatternExample {
  public static void main(String[] args) throws Exception{
    DocumentTemplate prototype = new DocumentTemplate();
    Factory factory = new Factory();
    
    System.out.println(factory.newDocument(prototype));
    System.out.println(factory.newDocument(prototype));
    System.out.println(factory.newDocument(prototype));
    
    DocumentTemplate specialPrototype = new SpecialDocumentTemplate();
    System.out.println(factory.newDocument(specialPrototype));
    System.out.println(factory.newDocument(specialPrototype));
    System.out.println(factory.newDocument(specialPrototype));
    
  }
  
  static class Factory{
    public <TDocument extends DocumentTemplate> IDocument newDocument(TDocument template){
      try {
        return IDocument.class.cast(template.clone());
      } catch (CloneNotSupportedException e) {
        throw new RuntimeException(e);
      }
    }
  }
  
  static interface IDocument {}

  static interface IDocumentTemplate extends IDocument{}
  
  @Prototype
  static class DocumentTemplate implements IDocumentTemplate, Cloneable{
    @Override
    public DocumentTemplate clone() throws CloneNotSupportedException {
      return (DocumentTemplate)super.clone();
    }
  }
  
  static class SpecialDocumentTemplate extends DocumentTemplate{}
  
}
Ausgabe:
Code:
de.tutorials.design.patterns.creational.PrototypePatternExample$DocumentTemplate@45bab50a
de.tutorials.design.patterns.creational.PrototypePatternExample$DocumentTemplate@64c3c749
de.tutorials.design.patterns.creational.PrototypePatternExample$DocumentTemplate@7150bd4d
de.tutorials.design.patterns.creational.PrototypePatternExample$SpecialDocumentTemplate@6bbc4459
de.tutorials.design.patterns.creational.PrototypePatternExample$SpecialDocumentTemplate@152b6651
de.tutorials.design.patterns.creational.PrototypePatternExample$SpecialDocumentTemplate@544a5ab2
Gruß Tom