`
三里小龙
  • 浏览: 85856 次
  • 性别: Icon_minigender_1
  • 来自: 孝感
社区版块
存档分类
最新评论

原型模式

阅读更多

用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象。

Prototype模式允许一个对象再创建另外一个可定制的对象,根本无需知道任何如何创建的细节,工作原理是:通过将一个原型对象传给那个要发动创建的对象,这个要发动创建的对象通过请求原型对象拷贝它们自己来实施创建。

 

package org.fanzone.pattern.prototype;


/** 

 * Title: base<br> 

 * Description: Prototype<br> 

 * Copyright: Copyright (c) 2011 <br> 

 * Create DateTime: Jul 7, 2011 8:34:01 PM <br> 

 * @author wangmeng

 */

public abstract class Animal implements Cloneable{


String statement;


public String getStatement() {

return statement;

}

public void setStatement(String statement) {

this.statement = statement;

}

public Object clone(){

Object obj = null;

try {

obj = this.getClass().newInstance();

} catch (InstantiationException e) {

e.printStackTrace();

} catch (IllegalAccessException e) {

e.printStackTrace();

}

return obj;

}

}

--------------------------------------------------------
package org.mars.pattern.prototype;

/** 
 * Title: base<br> 
 * Description: Concrete Prototype to clone.<br> 
 * Copyright: Copyright (c) 2011 <br> 
 * Create DateTime: Jul 7, 2011 8:44:24 PM <br> 
 * @author wangmeng
 */
public class DonaldDuck extends Animal {

public DonaldDuck() {
this.setStatement("Hi,everyone! I'm the Donald Duck.");
}
}
--------------------------------------------------------------------------
package org.mars.pattern.prototype;

/** 
 * Title: base<br> 
 * Description: Concrete Prototype to clone.<br> 
 * Copyright: Copyright (c) 2011 <br> 
 * Create DateTime: Jul 7, 2011 8:40:03 PM <br> 
 * @author wangmeng
 */
public class MickeyMouse extends Animal {

public MickeyMouse(){
this.setStatement("Hello,everybody! I'm the Mickey Mouse.");
}
}
----------------------------------------------------------------------------
package org.mars.pattern.prototype;

/** 
 * Title: base<br> 
 * Description: Client<br> 
 * Copyright: Copyright (c) 2011 <br> 
 * Create DateTime: Jul 7, 2011 8:48:31 PM <br> 
 * @author wangmeng
 */
public class Zoo {

private Animal animal;

public Zoo(Animal animal){
this.animal = animal;
}
public Animal makeAnimal(){
return (Animal) this.animal.clone();
}
@Override
protected Object clone() throws CloneNotSupportedException {
//This clone is not the same as the CLONE that defined by myself.
return super.clone();
}
public static void main(String[] args){
Zoo zoo = null;
Animal animal = null;
DonaldDuck duck = new DonaldDuck();
MickeyMouse mouse = new MickeyMouse();
//Make three ducks.
//Set the prototype.
zoo = new Zoo(duck);
for(int i=0; i<3; i++){
//#Get many objects by copying prototype.
//#(Just see the hashCode of object and the answer is front.)
animal = zoo.makeAnimal();
System.out.println(animal.hashCode() + ": " + animal.getStatement());
}
//Make two mice.
zoo = new Zoo(mouse);
for(int i=0; i<2; i++){
animal = zoo.makeAnimal();
System.out.println(animal.hashCode() + ": " + animal.getStatement());
}
}
}

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics