追MM之原型模式实现

简介:
跟MM用QQ聊天,一定要说些深情的话语了。但是,学理科的,哪有那多的情话啊,所以只能在网上搜集了好多肉麻的情话,需要时只要copy出来放到QQ里面就行了,这就是我的情话prototype了。
 
 
抽象原型角色:给出具体原型类的接口,一般要继承Cloneable接口
具体原型:被复制的对象,需要时,需要重写clone方法。在这里,实现clone 有深复制和前复制两种。
原型管理器:创建具体原型类的对象,并记录每一个被创建的对象。(init方法)
 
源代码
抽象原型
package prototype; 

public  interface Message  extends Cloneable{ 
/* 
*    信息都是可以被发送的 
*/
 
   public  void send(String content); 
    
   public String getContent(); 
    
   public Object clone(); 

 
具体原型
package prototype; 

import java.io.ByteArrayInputStream; 
import java.io.ByteArrayOutputStream; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.ObjectInputStream; 
import java.io.ObjectOutputStream; 
import java.io.Serializable; 

public  class LoveMessage  implements Message,Serializable { 

   private String content; 

   public  void send(String content) { 
     this.content = content; 
  } 

  @Override 
   public Object clone() { 
    ByteArrayOutputStream bo =  new ByteArrayOutputStream(); 
    ObjectOutputStream oo; 
    InputStream bi; 
    ObjectInputStream oi =  null
    Object target =  null
     try { 
      oo =  new ObjectOutputStream(bo); 
      oo.writeObject( this); 

      bi =  new ByteArrayInputStream(bo.toByteArray()); 
      oi =  new ObjectInputStream(bi); 
      target = oi.readObject(); 
    }  catch (IOException e) { 
      e.printStackTrace(); 
    }  catch (ClassNotFoundException e) { 
      e.printStackTrace(); 
    } 
     return target; 
  } 

   public String getContent() { 
     
     return  this.content; 
  } 


 
原型管理器
package prototype; 

import java.util.Vector; 

public  class MessageManager { 

   public Vector<Message> messages =  new Vector<Message>(); 
    
   public  void add(Message message){ 
    messages.add(message); 
  } 
    
   public Message getClone( int index){ 
    Message message = messages.get(index); 
     if( message !=  null){ 
       return (Message) message.clone(); 
    } 
     return  null
  } 

 
客户端
package prototype; 

public  class Client { 

   public  static  void init(MessageManager mgr){ 
    Message m1 =  new LoveMessage(); 
    m1.send( "我爱你,你却爱着他"); 
    mgr.add(m1);     
    Message m2 =  new LoveMessage(); 
    m2.send( "ILOVEYOU"); 
    mgr.add(m2); 
  } 
   public  static  void main(String[] args){ 
    MessageManager mgr =  new MessageManager(); 
    init(mgr); //初始化 
    System.out.println(mgr.getClone(1).getContent()); 
     
  } 

 
 
 本文转自 randy_shandong 51CTO博客,原文链接:http://blog.51cto.com/dba10g/229578,如需转载请自行联系原作者
相关文章
|
8月前
|
存储 设计模式 C++
2023-7-24-第二十二式备忘录模式
2023-7-24-第二十二式备忘录模式
68 0
|
9月前
|
设计模式
设计模式-原型模式(简历复印)
设计模式-原型模式(简历复印)
45 0
|
设计模式
设计模式——职责链模式实现消费时间计算
设计模式——职责链模式实现消费时间计算
61 0
设计模式——职责链模式实现消费时间计算
|
Web App开发 JavaScript 前端开发
【重温基础】7.时间对象
【重温基础】7.时间对象
115 0
SAP MM 史上最偷懒的盘点事务代码MI10
SAP MM 史上最偷懒的盘点事务代码MI10
SAP MM 史上最偷懒的盘点事务代码MI10