`
shuofenglxy
  • 浏览: 189628 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

菜鸟硕枫设计模式系列之5 原型模式

阅读更多
原型模式比较简单,就是利用object中的clone()方法做一次深度拷贝,复制一份原有对象即可。这种方式的好处在于原有对象的拷贝没有调用原有对象的New方法,也就没有触发原有对象的构造函数链,提高了对象制造效率。这种模式应用场景在于对象基本相同,除了个别属性字段有区分,可以复制后更改这些个别字段即可。

原型模式类图:
                              


具体实现demo:
原型类:
package protypePattern;

public class ProtoType implements Cloneable{

	private String name;
	private  String content =" , welcome to Taobao,have fun here.";
	
	public Object clone() {
			Object o =null;
		  try{
	        
			  o=(ProtoType)super.clone();
	         
		  }catch(CloneNotSupportedException e) {
	             
			  System.out.println(e.toString());
	         
		  }
	   
		  return o;
	}
	
	public void showGreetingwords(){
		System.out.println(this.getName()+content);
	}

	public String getContent() {
		return content;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getName() {
		return name;
	} 
}



测试类:
package protypePattern;

public class PrototypePatternTest {

	public static void main(String[] args){
		ProtoType greetingForLxy = new ProtoType();
		greetingForLxy.setName("lxy");
		greetingForLxy.showGreetingwords();
		
		System.out.println("-----------After cloning greetingForLxy---------");
		
		ProtoType greetingForShuofeng = (ProtoType) greetingForLxy.clone();
		greetingForShuofeng.setName("shuofeng");
		greetingForShuofeng.showGreetingwords();
		greetingForLxy.showGreetingwords();
	}
}


说明:Cloneable接口这里本没有必要去实现,因为直接复写object中的clone方法就可以了。这里实现这个接口只是为了说明原型模式用的是深克隆。
  • 大小: 3.9 KB
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics