设计模式-单例模式-饿汉单例与懒汉单例.

package 单例模式;

public class HungerSingleton {

    public static void main(String[] args) {

        HungerPunker hp = HungerPunker.getHP();
        HungerPunker hp1 = HungerPunker.getHP();
        System.out.println(hp);
        System.out.println(hp1);
    }

}


//another class
class HungerPunker{

   private HungerPunker(){

}
private static final HungerPunker hp = new HungerPunker(); public static HungerPunker getHP() { return hp; } }

 

 

package 单例模式;

public class LazySingleton {

    public static void main(String[] args) {

        // get the Lazy! instance!
        LazyPunker lp = LazyPunker.getLP();
        LazyPunker lp1 = LazyPunker.getLP();
        System.out.println(lp);
        System.out.println(lp1);
    }

}

// another class the LazyPunker~
class LazyPunker {

private LazyPunker(){

}
private static LazyPunker lp; public synchronized static LazyPunker getLP() { if (lp == null) { lp = new LazyPunker(); } return lp; } }

 

最近看<重构>这本书,原因是觉得代码打到一定程度之后会变得臃肿复杂,难以理解,如果没有一种好的设计模式,好的规范来框起来,

难免会变得没法去查看,更别说维护了.

关于设计模式还有很多书.

这次先贴上饿汉与懒汉的单例模式.

不知道哪位大仙取的这个名字...

posted @ 2018-06-08 00:14  ukyo--夜王  阅读(236)  评论(0编辑  收藏  举报