创建一个原型实例,通过拷贝这个原型来创建其他的此类对象。原型模式可以生成大量无上限的简单对象。
Prototype(ColorPrototype)
声明可克隆本身的接口
ConcretePrototype(Color)
实现克隆方法
Client(ColorManager)
通过请求一个原型克隆,创建一个新对象。
代码
//Prototype
public abstract class ColorPrototype implements Cloneable{
public abstract ColorPrototype cloneMe() throws CloneNotSupportedException;
}
//ConcretePrototype
public class Color extends ColorPrototype{
private int red, green, blue;
public Color(int red, int green, int blue){
this.red=red;
this.green=green;
this.blue=blue;
}
public ColorPrototype cloneMe() throws CloneNotSupportedException{
//浅拷贝
return (ColorPrototype)super.clone();
}
public void Display(){
System.out.println(“RGB values are :” + red +”,”+ green+”,”+blue);
}
}
//prototype manager
import java.util.*;
public class ColorManager{
Hashtable colors=new Hashtable();
public ColorPrototype getColor(String name){
return (ColorPrototype)colors.get(name);
}
public void setColor(String name, ColorPrototype value){
colors.add(name, value);
}
}
//client
//prototypeApp test
public class PrototypeApp{
public static void main(String[] args){
ColorManager colormanager=new ColorManager();
//初始化标准color
colormanager.setColor(“red”,new Color(255,0,0));
colormanager.setColor(“green”,new Color(0,255,0));
colormanager.setColor(“blue”,new Color(.0,0,255));
//用户增加个性color
colormanager.setColor(“angry”,new Color(255,54,0));
colormanager.setColor(“peace”,new Color(128,211,128));
colormanager.setColor(“flame”,new Color(.211,34,20));
//用户使用选定color
String colorName=”red”;
Color cl=(Color)colormanager.getColor(colorName).cloneMe();
cl.Display();
String colorName=”peace”;
Color cl=(Color)colormanager.getColor(colorName).cloneMe();
cl.Display();
String colorName=”flame”;
Color cl=(Color)colormanager.getColor(colorName).cloneMe();
cl.Display();
结果
Output
RGB values are: 255,0,0
RGB values are: 128,211,128
RGB values are: 211,34,20