Java单例和原型

单例模式作用:提供系统资源,只有一个。

原型作用:创建多个相同的对象,复制本身。

单例的运行时产生public class Singleton1 {

private static Singleton1 singleton;
  private static Singleton2 singleton
  private Singleton1(){

  }
public static synchronized Singleton1 getSingleton(){ if(singleton==null){ singleton=new Singleton1(); }return singleton; } }

单例的加载时产生:

public class Singleton2 {
    private static Singleton2 singleton=new Singleton2();
private Singleton1(){

  }
public static Singleton2 getSingleton(){ return singleton; } }

枚举方式:

public enum Singleton3 {
    singleton3;
}

原型的实现方式:

 
/*
 * clone 分深拷贝和浅拷贝
 * 拷贝对象的引用,需要重写该对象的clone()方法,
 * 并且引用对象的clone()方法也需要重写
 * 绝对的深拷贝不存在
 */
public class Body implements Cloneable{
    private Head head;
     
    public Head getHead() {
        return head;
    }
    public void setHead(Head head) {
        this.head = head;
    }
    @Override
    protected Object clone() throws CloneNotSupportedException {
        Body body=(Body)super.clone();
        body.head=(Head) this.head.clone();
        return body;
    }
}
class Head implements Cloneable{
    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
}

 


 

posted on 2016-10-27 12:21  flovato  阅读(227)  评论(0编辑  收藏  举报

导航