根据实例原型、实例模版来生成新的实例
java中,可以使用clone创建出实例的副本
/**
* 原型
*/
public interface Product extends Cloneable {
public abstract void use(String s);
public abstract Product createClone();
}
/**
* 具体的原型 ,负责实现复制现有实例并生成新实例
*/
public class MessageBox implements Product {
private char decochar;
public MessageBox(char decochar) {
this.decochar = decochar;
}
@Override
public void use(String s) {
int length = s.getBytes().length;
for (int i = 0; i < length + 4; i++) {
System.out.print(decochar);
}
System.out.println("");
System.out.println(decochar+" "+s+" "+decochar);
for (int i = 0; i < length + 4; i++) {
System.out.print(decochar);
}
System.out.println("");
}
@Override
public Product createClone() {
Product p = null;
try {
p = (Product) clone();//Object中的clone,Product需要继承Cloneable
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return p;
}
}
/**
* 具体的原型
*/
public class UnderlinePen implements Product {
private char ulchar;
public UnderlinePen(char ulchar) {
this.ulchar = ulchar;
}
@Override
public void use(String s) {
int length = s.getBytes().length;
System.out.println("""+s+""");
System.out.print(" ");
for (int i = 0; i < length + 4; 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;
}
}
/**
* 使用者 ,负责使用复制实例的方法生成新的实例
*/
public class Manager {
private HashMap showcase = new HashMap();
//使用字符串为生成的实例命名
public void register(String name,Product proto){
showcase.put(name,proto);
}
public Product create(String protoname){
Product p = (Product) showcase.get(protoname);
return p.createClone();
}
}
public class Main {
public static void main(String[] args){
Manager manager = new Manager();
UnderlinePen underlinePen = new UnderlinePen('~');
MessageBox mbox = new MessageBox('*');
MessageBox sbox = new MessageBox('/');
manager.register("message",underlinePen);
manager.register("warning",mbox);
manager.register("sbox",sbox);
Product p1 = manager.create("message");
p1.use("hello");
Product p2 = manager.create("warning");
p2.use("hello");
Product p3 = manager.create("sbox");
p3.use("hello");
/*
* "hello"
* ~~~~~~~~~
* *********
* * hello *
* *********
* /////////
* / hello /
* /////////
*/
}
}
Cloneable接口是标记可以使用clone方法的
clone方法进行的是浅复制,当字段中保存的是数组时,只会复制该数组的引用