1
2
3
4
5 import java.util.*;
6
7 interface Product extends Cloneable {
8 public abstract void use(String s);
9 public abstract Product createClone();
10 }
11
12 class Manager {
13 private Hashtable showcase = new Hashtable();
14 public void register(String name, Product proto) {
15 showcase.put(name, proto);
16 }
17 public Product create(String protoname) {
18 Product p = (Product)showcase.get(protoname);
19 return p.createClone();
20 }
21 }
22
23 class MessageBox implements Product {
24 private char decochar;
25 public MessageBox(char decochar) {
26 this.decochar = decochar;
27 }
28 public void use(String s) {
29 int length = s.getBytes().length;
30 for(int i=0; i < length+4; i++) {
31 System.out.print(decochar);
32 }
33 System.out.println("");
34 System.out.println(decochar+" "+s+" "+decochar);
35 for(int i=0; i < length+4; i++) {
36 System.out.print(decochar);
37 }
38 System.out.println("");
39 }
40 public Product createClone() {
41 Product p = null;
42 try {
43 p = (Product)clone();
44 } catch(CloneNotSupportedException e) {
45 e.printStackTrace();
46 }
47 return p;
48 }
49 }
50
51 class UnderlinePen implements Product {
52 private char ulchar;
53 public UnderlinePen(char ulchar) {
54 this.ulchar = ulchar;
55 }
56 public void use(String s) {
57 int length = s.getBytes().length;
58 System.out.println("\""+s+"\"");
59 System.out.print(" ");
60 for(int i=0; i < length; i++) {
61 System.out.print(ulchar);
62 }
63 System.out.println("");
64 }
65 public Product createClone() {
66 Product p = null;
67 try {
68 p = (Product)clone();
69 } catch(CloneNotSupportedException e) {
70 e.printStackTrace();
71 }
72 return p;
73 }
74 }
75
76 public class PrototypeDisplay {
77 public static void main(String[] args) {
78 Manager manager = new Manager();
79 UnderlinePen upen = new UnderlinePen('~');
80 MessageBox mbox = new MessageBox('*');
81 MessageBox sbox = new MessageBox('/');
82 manager.register("strong message", upen);
83 manager.register("warning box", mbox);
84 manager.register("slash box", sbox);
85
86 Product p1 = manager.create("strong message");
87 p1.use("Hello, world.");
88 Product p2 = manager.create("warning box");
89 p2.use("Warning");
90 Product p3 = manager.create("slash box");
91 p3.use("Slash");
92 }
93 }