设计模式学习之原型模式

如果说,简单工厂模式、工厂模式、抽象工厂模式、构建者模式都一定程度上解决了耦合的问题,那么接下来要学习的原型(Prototype)模式则一定程度上解决了初始化速率的问题。下面是原型模式的例子,需要特别说明的是,java中除了8中基本类型,都是引用类型,但是String只能说是一种特殊的引用类型,因为在内存分配的时候,String的值也跟8种基本类型一样,分配在常量池中。以下是转发的例子:

原型模式是一种创建型设计模式,它通过复制一个已经存在的实例来返回新的实例,而不是新建实例.被复制的实例就是我们所称的原型,这个原型是可定制的.
原型模式多用于创建复杂的或者耗时的实例, 因为这种情况下,复制一个已经存在的实例可以使程序运行更高效,或者创建值相等,只是命名不一样的同类数据.

原型模式中的拷贝分为"浅拷贝"和"深拷贝":
浅拷贝: 对值类型的成员变量进行值的复制,对引用类型的成员变量只复制引用,不复制引用的对象.
深拷贝: 对值类型的成员变量进行值的复制,对引用类型的成员变量也进行引用对象的复制.

类图:

实例一:浅拷贝
public class Prototype implements Cloneable {
 private String name;//值类型

 public String getName() {
  return name;
 }

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

 public Object clone() {
  try {
   return super.clone();
  } catch (CloneNotSupportedException e) {   
   e.printStackTrace();
   return null;
  }
 } 
 
}

public class TestMain {

 public static void main(String[] args) {
  testPrototype();
 }
 
 private static void testPrototype(){
  Prototype pro = new Prototype();
  pro.setName("original object");
  Prototype pro1 = (Prototype)pro.clone();
  pro.setName("changed object1");
  
  System.out.println("original object:" + pro.getName());
  System.out.println("cloned object:" + pro1.getName());
  
 }

}
结果:
original object:changed object1
cloned object:original object


实例二: 浅拷贝
public class Prototype{
 private String name;

 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 } 
 
}
public class NewPrototype implements Cloneable {
 
 private String id;//值类型
 
 public String getId() {
  return id;
 }

 public void setId(String id) {
  this.id = id;
 }

 private Prototype prototype;//引用类型
 
 public Prototype getPrototype() {
  return prototype;
 }

 public void setPrototype(Prototype prototype) {
  this.prototype = prototype;
 }


 public Object clone(){ 
  try {
   return super.clone();
  } catch (CloneNotSupportedException e) {
   e.printStackTrace();
   return null;
  }  
 }

}
public class TestMain {

 public static void main(String[] args) {
  // TODO Auto-generated method stub
  testPrototype();
 }
 
 private static void testPrototype(){
  Prototype pro = new Prototype();
  pro.setName("original object");
  NewPrototype newObj = new NewPrototype();
  newObj.setId("test1");
  newObj.setPrototype(pro);
  
  NewPrototype copyObj = (NewPrototype)newObj.clone();
  copyObj.setId("testCopy");
  copyObj.getPrototype().setName("changed object");
  
  System.out.println("original object id:" + newObj.getId());
  System.out.println("original object name:" + newObj.getPrototype().getName());
  
  System.out.println("cloned object id:" + copyObj.getId());
  System.out.println("cloned object name:" + copyObj.getPrototype().getName());
  
 }

}

结果:
original object id:test1
original object name:changed object
cloned object id:testCopy
cloned object name:changed object


实例三: 深拷贝
public class Prototype implements Cloneable {
 private String name;

 public String getName() {
  return name;
 }

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

 public Object clone() {
  try { 
   return super.clone();
  } catch (CloneNotSupportedException e) {   
   e.printStackTrace();
   return null;
  }
 } 
 
}

public class NewPrototype implements Cloneable {
 
 private String id;
 
 public String getId() {
  return id;
 }

 public void setId(String id) {
  this.id = id;
 }

 private Prototype prototype;
 
 public Prototype getPrototype() {
  return prototype;
 }

 public void setPrototype(Prototype prototype) {
  this.prototype = prototype;
 }


 public Object clone(){
  NewPrototype ret = null;
  try {
   ret = (NewPrototype)super.clone();
   ret.prototype = (Prototype)this.prototype.clone();
   return ret;
  } catch (CloneNotSupportedException e) {
   e.printStackTrace();
   return null;
  }  
 }

}

public class TestMain {

 /**
  * @param args
  */
 public static void main(String[] args) {
  testDeepCopy();
 }
 
 private static void testDeepCopy(){
  Prototype pro = new Prototype();
  pro.setName("original object");
  NewPrototype newObj = new NewPrototype();
  newObj.setId("test1");
  newObj.setPrototype(pro);
  
  NewPrototype copyObj = (NewPrototype)newObj.clone();
  copyObj.setId("testCopy");
  copyObj.getPrototype().setName("changed object");
  
  System.out.println("original object id:" + newObj.getId());
  System.out.println("original object name:" + newObj.getPrototype().getName());
  
  System.out.println("cloned object id:" + copyObj.getId());
  System.out.println("cloned object name:" + copyObj.getPrototype().getName());
  
 }

}

结果:
original object id:test1
original object name:original object
cloned object id:testCopy
cloned object name:changed object

实例四: 利用串行化来做深复制
把对象写道流里的过程是串行化(Serilization)过程;把对象从流中读出来是并行化(Deserialization)过程. 写在流里的是对象的一个拷贝,然后再从流里读出来重建对象.
public class PrototypeSe implements Serializable {

 private String name;

 public String getName() {
  return name;
 }

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

}

public class NewPrototypeSe implements Serializable {
 
 private String id;
 
 public String getId() {
  return id;
 }

 public void setId(String id) {
  this.id = id;
 }

 private PrototypeSe prototype;
 
 public PrototypeSe getPrototype() {
  return prototype;
 }

 public void setPrototype(PrototypeSe prototype) {
  this.prototype = prototype;
 }
 
 public Object deepClone(){
  try {
   ByteArrayOutputStream bo = new ByteArrayOutputStream();
   ObjectOutputStream oo = new ObjectOutputStream(bo);   
   oo.writeObject(this);   
   
   ByteArrayInputStream bi = new ByteArrayInputStream(bo.toByteArray());
   ObjectInputStream oi = new ObjectInputStream(bi);
   return oi.readObject(); 
  } catch (IOException | ClassNotFoundException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
   return null;
  }
 }

}

public class TestDeepClone {

 public static void main(String[] args) {
  // TODO Auto-generated method stub
  PrototypeSe po = new PrototypeSe();
  po.setName("test1");
  NewPrototypeSe se = new NewPrototypeSe();
  se.setPrototype(po);
  
  NewPrototypeSe deepClone = (NewPrototypeSe)se.deepClone();
  deepClone.getPrototype().setName("test2");
  
  System.out.println("original name:" + se.getPrototype().getName());
  System.out.println("cloned name:" + deepClone.getPrototype().getName());

 }
}
结果:
original name:test1
cloned name:test2


总结:原型(Prototype)模式能提高产生新对象的速度,需要继承Cloneable接口,重写clone()。深拷贝其实是对浅拷贝进行了迭代拷贝。


转自:http://www.cnblogs.com/itTeacher/archive/2012/12/02/2797857.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
创建型: 1. 单件模式(Singleton Pattern) 2. 抽象工厂(Abstract Factory) 3. 建造者模式(Builder) 4. 工厂方法模式(Factory Method) 5. 原型模式(Prototype) 结构型: 6. 适配器模式(Adapter Pattern) 7. 桥接模式(Bridge Pattern) 8. 装饰模式(Decorator Pattern) 9. 组合模式(Composite Pattern) 10. 外观模式(Facade Pattern) 11. 享元模式(Flyweight Pattern) 12. 代理模式(Proxy Pattern) 13. 模板方法(Template Method) 14. 命令模式(Command Pattern) 15. 迭代器模式(Iterator Pattern) 行为型: 16. 观察者模式(Observer Pattern) 17. 解释器模式(Interpreter Pattern) 18. 中介者模式(Mediator Pattern) 19. 职责链模式(Chain of Responsibility Pattern) 20. 备忘录模式(Memento Pattern) 21. 策略模式(Strategy Pattern) 22. 访问者模式(Visitor Pattern) 23. 状态模式(State Pattern) 工程结构 ├─01.Singleton │ ├─html │ └─MySingleton │ ├─bin │ │ └─Debug │ ├─obj │ │ └─Debug │ │ └─TempPE │ └─Properties ├─02.ChainOfResponsibility │ ├─html │ ├─My2ChainOfResponsibility │ │ ├─bin │ │ │ └─Debug │ │ ├─obj │ │ │ └─Debug │ │ │ └─TempPE │ │ └─Properties │ └─MyChainOfResponsibility │ ├─bin │ │ └─Debug │ ├─obj │ │ └─Debug │ │ ├─Refactor │ │ └─TempPE │ └─Properties ├─03.FactoryMethodMode │ ├─FactoryMethodMode │ │ ├─bin │ │ │ └─Debug │ │ ├─obj │ │ │ └─Debug │ │ │ └─TempPE │ │ └─Properties │ └─html ├─04.AbstractFactory │ ├─04.1.SimpleFactory │ │ ├─html │ │ └─SimpleFactory │ │ ├─bin │ │ │ └─Debug │ │ ├─obj │ │ │ └─Debug │ │ │ └─TempPE │ │ └─Properties │ ├─AbstractFactory │ │ ├─bin │ │ │ └─Debug │ │ ├─obj │ │ │ └─Debug │ │ │ └─TempPE │ │ └─Properties │ └─html ├─05.BuilderPattern │ ├─html │ └─MyBuilderPattern │ ├─bin │ │ └─Debug │ ├─obj │ │ └─Debug │ │ └─TempPE │ └─Properties ├─06.PrototypePattern │ ├─html │ │ └─C#设计模式(6)——原型模式(Prototype Patt O技术博客_files │ └─PrototypePattern │ ├─bin │ │ └─Debug │ ├─obj │ │ └─Debug │ │ └─TempPE │ └─Properties ├─07.AdapterPattern │ ├─html │ └─MyAdapterPattern │ ├─bin │ │ └─Debug │ ├─obj │ │ └─Debug │ │ └─TempPE │ └─Properties ├─08.BridgePattern │ ├─html │ └─MyBridgePattern │ ├─bin │ │ └─Debug │ ├─obj │ │ └─Debug │ │ └─TempPE │ └─Properties ├─09.DecoratorPattern │ ├─html │ └─MyDecoratorPattern │ ├─bin │ │ └─Debug │ ├─obj │ │ └─Debug │ │ └─TempPE │ └─Properties ├─10.CompositePattern │ ├─html │ └─MyCompositePattern │ ├─bin │ │ └─Debug │ ├─obj │ │ └─Debug │ │ └─TempPE │ └─Properties ├─11.FacadePattern │ ├─html │ └─MyFacadePattern │ ├─bin │ │ └─Debug │ ├─obj │ │ └─Debug │ │ └─TempPE │ └─Properties ├─12.FlyweightPattern │ ├─html │ └─MyFlyweightPattern │ ├─bin │ │ └─Debug │ ├─obj │ │ └─Debug │ │ └─TempPE │ └─Properties ├─13.ProxyPattern │ ├─html │ └─MyProxyPattern │ ├─bin │ │ └─Debug │ ├─obj │ │ └─Debug │ │ └─TempPE │ └─Properties ├─14.TemplateMethod │ ├─html │ └─MyTemplateMethod │ ├─bin │ │ └─Debug │ ├─obj │ │ └─Debug │ │ └─TempPE │ └─Properties ├─15.VisitorPattern │ ├─html │ └─MyVisitorPattern │ ├─bin │ │ └─Debug │ ├─obj │ │ └─Debug │ │ └─TempPE │ └─Properties ├─16.StrategyPattern │ ├─html │ └─MyStrategyPattern │ ├─bin │ │ └─Debug │ ├─obj │ │ └─Debug │ │ └─TempPE │ └─Properties ├─17.StatePattern │ ├─html │ └─StatePattern │ ├─bin │ │ └─Debug │ ├─obj │ │ └─Debug │ │ └─TempPE │ └─Properties ├─18.MementoPattern │ ├─html │ └─MementoPattern │ ├─bin │ │ └─Debug │ ├─obj │ │ └─Debug │ │ └─TempPE │ └─Properties ├─19.MediatorPattern │ ├─html │ └─MediatorPattern │ ├─bin │ │ └─Debug │ ├─obj │ │ └─Debug │ │ └─TempPE │ └─Properties ├─20.OberverPattern │ ├─CatOberverPattern │ │ ├─bin │ │ │ └─Debug │ │ ├─obj │ │ │ └─Debug │ │ │ └─TempPE │ │ └─Properties │ ├─html │ └─MyOberverPattern │ ├─bin │ │ └─Debug │ ├─obj │ │ └─Debug │ │ └─TempPE │ └─Properties ├─21.IteratorPattern │ ├─html │ └─IteratorPattern │ ├─bin │ │ └─Debug │ ├─obj │ │ └─Debug │ │ └─TempPE │ └─Properties ├─22.InterpreterPattern │ ├─html │ └─MyInterpreterPattern │ ├─bin │ │ └─Debug │ ├─obj │ │ └─Debug │ │ └─TempPE │ └─Properties └─23.CommandPattern ├─html └─MyCommandPattern ├─bin │ └─Debug ├─obj │ └─Debug │ └─TempPE └─Properties

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值