从一个对象实例产生出另外一个新对象实例,即通过拷贝原型来创建新的对象,减少类的数目。
组成:
客户角色:使用原型对象的客户程序
抽象原型角色:定义具体原型对象必须实现的接口(如果要提供深拷贝,则必须具有实现clone的规定)
具体原型角色:从抽象原型派生而来,是客户程序使用的对象,即被复制的对象。此角色实现抽象原型角色所要求的的接口。
对客户隐藏了具体的产品类,因此焦山了客户知道的名字的数目。运行时刻增加和删除产品,动态配置应用。克隆一个原型类似于实例化一个类,原型模式极大的减少了系统所需的类的数目。
1.客户角色Manager
import java.util.*;
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();
}
}
2.抽象原型
import java.lang.Cloneable;
public interface Product extends Cloneable {
public abstract void use(String s);
public abstract Product createClone();
}
3.具体原型MessageBox
public class MessageBox implements Product {
private char decochar;
public MessageBox(char decochar) {
this.decochar = decochar;
}
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("");
}
public Product createClone() {
Product p = null;
try {
p = (Product)clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return p;
}
}
4.具体原型UnderlinePen
public class UnderlinePen implements Product {
private char ulchar;
public UnderlinePen(char ulchar) {
this.ulchar = ulchar;
}
public void use(String s) {
int length = s.getBytes().length;
System.out.println("\"" + s + "\"");
System.out.print(" ");
for (int i = 0; i < length; i++) {
System.out.print(ulchar);
}
System.out.println("");
}
public Product createClone() {
Product p = null;
try {
p = (Product)clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return p;
}
}
5.主函数Main
public class Main {
public static void main(String[] args) {
Manager manager = new Manager();
UnderlinePen upen = new UnderlinePen('~');
MessageBox mbox = new MessageBox('*');
MessageBox sbox = new MessageBox('/');
manager.register("strong message", upen);
manager.register("warning box", mbox);
manager.register("slash box", sbox);
Product p1 = manager.create("strong message");
p1.use("Hello, world.");
Product p2 = manager.create("warning box");
p2.use("Hello, world.");
Product p3 = manager.create("slash box");
p3.use("Hello, world.");
}
}