JavaPrototype模式
本文最后更新于:1 年前
通过复制生成实例
1 - 声明了抽象方法use和createClone的接口
public interface Product extends Cloneable{
public abstract void use(String s);
public abstract Product createClone();
}
2 - 调用createClone方法复制实例的类
import java.util.*;
public class Manager {
private HashMap<String, Product> showcase = new HashMap<String, Product>();
public void register(String name, Product proto){
showcase.put(name, proto);
}
public Product create(String protoname){
Product p = showcase.get(protoname);
return p.createClone();
}
}
被复制对象的类必须实现java.lang.Clonable接口
3 - 将字符串放入方框中并使其显示出来的类, 实现了use方法和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();
}catch (CloneNotSupportedException e){
e.printStackTrace();
}
return p;
}
}
4 - 给字符串加下划线并使其显示出来的类,实现了use方法和createClone方法
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; 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;
}
}
5 - 测试程序行为的类
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.");
}
}
6 - 输出示例
"Hello, world."
~~~~~~~~~~~~~
*****************
* Hello, world. *
*****************
/////////////////
/ Hello, world. /
/////////////////
在一些情况下,我们很难将种类繁多的对象整合到一个类中或者根据一个类来生成它的的实例,这个时候我们就可以以复制的方式,来根据实例生成新的实例.
本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!