原创作品,允许转载,转载时请务必以超链接形式标明文章 原始出处 、作者信息和本声明。否则将追究法律责任。http://dba10g.blog.51cto.com/764602/229578
跟MM用QQ聊天,一定要说些深情的话语了。但是,学理科的,哪有那多的情话啊,所以只能在网上搜集了好多肉麻的情话,需要时只要copy出来放到QQ里面就行了,这就是我的情话prototype了。
 
追MM之原型模式实现
 
抽象原型角色:给出具体原型类的接口,一般要继承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()); 
     
  } 

 
 
 
 

本文出自 “简单” 博客,请务必保留此出处http://dba10g.blog.51cto.com/764602/229578

相关文章:

  • 2022-12-23
  • 2021-05-22
  • 2021-07-09
  • 2021-08-06
  • 2021-09-22
  • 2021-12-27
  • 2021-09-05
猜你喜欢
  • 2021-08-28
  • 2022-12-23
  • 2021-07-31
  • 2021-09-23
  • 2021-10-04
  • 2022-12-23
相关资源
相似解决方案