用原型实例指定创建对象的种类,并且都过拷贝这些原型建建新的对象。
prototype模式充许一个对象再创建另一个可定制的对象,根本无需知道创建的细节。
java中提供了clone()来实现对象克隆。所以prototype模式变得了很简单。请参考以下例程:
package com.pdw.pattern;
abstract class AbsHello implements Cloneable{
String username;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public abstract void sayHello();
public Object clone(){
Object object=null;
try{
object=super.clone();
}catch(Exception e){
System.err.println(e);
}
return object;
}
}
class OneHello extends AbsHello{
public OneHello(){
setUsername("peidw");
}
@Override
public void sayHello() {
// TODO Auto-generated method stub
System.out.println("OneHello-->SayHello to "+username);
}
}
class TwoHello extends AbsHello{
public TwoHello(){
setUsername("pxm");
}
@Override
public void sayHello() {
// TODO Auto-generated method stub
System.out.println("TwoHello-->sayHello to "+username);
}
}
public class Prototype {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
AbsHello oneh=new OneHello();
AbsHello twoh=new TwoHello();
oneh.sayHello();
twoh.sayHello();
}
}
posted on 2006-06-28 23:26
有猫相伴的日子 阅读(232)
评论(0) 编辑 收藏 所属分类:
Patterns