java-设计模式

来源:互联网 发布:linux rc.local sh 编辑:程序博客网 时间:2024/05/17 22:41

一.单列设计模式
单列模式:一个实例(servlet)
这里写图片描述
懒汉模式:(单线程和多线程)
1.私有化一个静态的属性对象,赋值为null
2.私有构造方法
3.一个公共的静态方法,(判断并且创建对象)返回对象
饿汉模式:1.私有化一个静态的属性对象
2.私有构造方法
3.一个公共的静态方法,返回对象
延迟加载(构建内部类)

饿汉模式

Single的饿汉类public class Single {    private static final Single s=new Single();    private Single(){}    public static Single getinstance()    {        return s;    }    }public class Single_Test {    public static void main(String[] args) {        // TODO Auto-generated method stub        Single s1=Single.getinstance();        Single s2=Single.getinstance();        System.out.println(s1==s2);//此处相等,饿汉模式true    }}类加载时,静态变量初始化,类的私有构造方法会被调用

饿汉模式的延迟加载

public class Single {    private Single(){}    public static Single getinstance()    {        return Single_Inner.s;    }    public static class Single_Inner{        private static Single s=new Single();//此处为延迟加载    }}Test类public class Single_Test {    public static void main(String[] args) {        // TODO Auto-generated method stub        Single s1=Single.getinstance();        Single s2=Single.getinstance();        System.out.println(s1==s2);//此处相等,饿汉模式true    }}

懒汉模式

public class Single {    //懒汉模式    private static Single s=null;    private Single(){}    public static Single getinstance()    {        if(s==null)        {            s=new Single();        }        return s;    }}public class Single_Test {    public static void main(String[] args) {        // TODO Auto-generated method stub        Single s1=Single.getinstance();        Single s2=Single.getinstance();        System.out.println(s1==s2);//此处相等,懒汉模式true    }}

二.享元设计模式