Skip to content

Instantly share code, notes, and snippets.

@shoheiyokoyama
Last active November 6, 2016 07:18
Show Gist options
  • Save shoheiyokoyama/9d7cef99ac3a8c2cd8c0 to your computer and use it in GitHub Desktop.
Save shoheiyokoyama/9d7cef99ac3a8c2cd8c0 to your computer and use it in GitHub Desktop.
デザインパターン「Prototype」 ref: http://qiita.com/shoheiyokoyama/items/61826e158b3c4a259065
public interface Product extends Cloneable {
public abstract void use(String s);
public abstract Product createClone();
}
Git Hub
-------
@@@@@@@@@
@ Qiita @
@@@@@@@@@
♪♪♪♪♪♪♪♪
♪ Java ♪
♪♪♪♪♪♪♪♪
public static void main(String[] args) {
Manager manager = new Manager();
UnderLinepen upen = new UnderLinePen('-');
MessageBox mbox = new MessageBox('@');
MessageBox sbox = new MessageBox('♪');
manager.register("stong message", upen);
manager.register("warning box", mbox);
manager.register("slash box", sbox);
Product p1 = manager.create("stong message");
p1.use("Git Hub");
Product p2 = manager.create("warning box");
p2.use("Qiita");
Product p3 = manager.create("slash box");
p3.use("Java");
}
public class Manager {
private HashMap showcase = new HashMap();
public void register(String name, Product prototype) {
showcase.put(name, prototype);
}
public Product create(String protoname) {
//※
Product p = (Product)showcase.get(protoname);
return p.createClone();
}
}
public class MessageBox implements Product {
private char decoChar;
public MessageBox(char decoChar) {
this.decoChar = decoChar;
}
@Override
public void use(String string) {
int length = string.getBytes().length;
for (int i = 0; i < length + 4; i++) {
System.out.print(decoChar);
}
System.out.println("");
System.out.println(decoChar + " " + string + " " + decoChar);
for (int i = 0; i < length + 4; i++) {
System.out.print(decoChar);
}
System.out.println("");
}
//Productインターフェイスを実装してなければCloneNotSupportedExceptionが投げられる
@Override
public Product createClone() {
Product p = null;
try {
p = (Product)clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return p;
}
}
public interface Product extends Cloneable {
public abstract void use(String s);
public abstract Product createClone();
}
public class UnderLinePen implements Product {
private char ulChar;
public UnderLinePen(char ulChar) {
this.ulChar = ulChar;
}
@Override
public void use(String string) {
int length = string.getBytes().length;
System.out.println(string);
System.out.print("");
for (int i = 0; i < length; i++) {
System.out.print(ulChar);
}
System.out.println("");
}
@Override
public Product createClone() {
Product p = null;
try {
p = (Product)clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return p;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment