溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

什么是單例模式與原型模式

發(fā)布時(shí)間:2021-10-11 11:28:21 來(lái)源:億速云 閱讀:165 作者:iii 欄目:編程語(yǔ)言

本篇內(nèi)容主要講解“什么是單例模式與原型模式”,感興趣的朋友不妨來(lái)看看。本文介紹的方法操作簡(jiǎn)單快捷,實(shí)用性強(qiáng)。下面就讓小編來(lái)帶大家學(xué)習(xí)“什么是單例模式與原型模式”吧!

單例模式

單例模式應(yīng)該算是最常用的設(shè)計(jì)模式了叭,著名的雙重校驗(yàn)也是單例模式的一種實(shí)現(xiàn)。所謂單例模式就是用來(lái)保證一個(gè)對(duì)象只能創(chuàng)建一個(gè)實(shí)例,除此之外,它還提供了對(duì)實(shí)例的全局訪問(wèn)方式。

單例模式UML類圖

什么是單例模式與原型模式

單例模式餓漢式

所謂餓漢式,人餓了看到啥都想吃。同樣,不管需不需要這個(gè)實(shí)例,反正我都先給你創(chuàng)建好。

普通實(shí)現(xiàn)

public class SingletonHungry {
    
    //在類加載的時(shí)候就已經(jīng)創(chuàng)建了唯一的實(shí)例
    private static final SingletonHungry instance = new SingletonHungry();
    
    //保證外部不能調(diào)用構(gòu)造函數(shù)
    private SingletonHungry() {
    }

    //外部調(diào)用這個(gè)方法,就返回實(shí)例
    public static SingletonHungry getInstance() {
        return instance;
    }
    
    //類中其它方法,盡量是static
    public static void func(){}
    
}

靜態(tài)代碼塊

public class SingletonHungryStatic {
    //其實(shí)就是把new的部分移到了靜態(tài)代碼塊中
    private static SingletonHungryStatic instance = null;
    static {
        instance = new SingletonHungryStatic();
    }

    private SingletonHungryStatic() {
    }

    public static SingletonHungryStatic getInstance() {
        return instance;
    }

    //類中其它方法,盡量是static
    public static void func(){}
}

單例模式懶漢式

所謂懶漢,就是要不是有人催促,就不肯去勞動(dòng)。同理,只有你找我要這個(gè)是,才創(chuàng)建出來(lái)。

什么是單例模式與原型模式

普通實(shí)現(xiàn)

public class SingletonLazy {
    //volatile之前已經(jīng)講過(guò),防止指令的重排序,這個(gè)volatile是不能省略的
    private static volatile SingletonLazy instance = null;
    private SingletonLazy(){}

    public static SingletonLazy getInstance() throws Exception {

        if(instance == null) {
            synchronized (SingletonLazy.class) {
                if(instance == null) {
                    instance = new SingletonLazy();
                }
            }
        }
        return instance;
    }
}

靜態(tài)內(nèi)部類

public class SingletonLazyStatic {
    
    /**
     * 靜態(tài)內(nèi)部類注意事項(xiàng)
     *  1. 類加載的時(shí),靜態(tài)內(nèi)部類不會(huì)隨著加載
     *  2. 靜態(tài)內(nèi)部類只會(huì)初始化一次
     *  3. 線程安全的
     */
    
    private static class StaticClassInstance{
        private static final SingletonLazyStatic INSTACE = new SingletonLazyStatic();
    }
    private SingletonLazyStatic() {
    }
    
    public static SingletonLazyStatic getInstance() {
        return StaticClassInstance.INSTACE;
    }
}

其實(shí)還有一種更為優(yōu)雅的實(shí)現(xiàn)方式,那就是使用枚舉,不過(guò)之前看那些文章好像都說(shuō)什么少用,所以本文就不粘出來(lái)給各位增加學(xué)習(xí)成本了。

Client

public class Client {
    public static void main(String[] args) throws Exception {
//        hungry();
//        hungryStatic();
//        lazy();
        lazyStatic();
    }

    public static void lazyStatic() {
        SingletonLazyStatic instance = SingletonLazyStatic.getInstance();
        SingletonLazyStatic instance1 = SingletonLazyStatic.getInstance();
        System.out.println(instance);
        System.out.println(instance1);
    }
	
    //下面3中和上面實(shí)現(xiàn)是類似的,只需要更換類名
    public static void lazy() throws Exception {}

    public static void hungry() {}

    public static void hungryStatic() {}

}

原型模式

原型模式聽(tīng)起來(lái)高大上,其實(shí)就是一種克隆對(duì)象的方法。

說(shuō)到克隆不得不簡(jiǎn)單說(shuō)下淺拷貝和深拷貝,淺拷貝就是指兩個(gè)指針指向了同一個(gè)對(duì)象,原對(duì)象和拷貝對(duì)象只要有一個(gè)修改,另外一個(gè)也隨著修改。深拷貝是指,重新創(chuàng)建了一個(gè)和原對(duì)象一模一樣內(nèi)容的拷貝對(duì)象,兩者是獨(dú)立的?;緮?shù)據(jù)類型是不參與拷貝過(guò)程的

Prototype: 抽象原型類,聲明了clone方法的接口或者基類,其中clone方法必須由派生對(duì)象實(shí)現(xiàn)。

Concrete Prototype: 具體實(shí)現(xiàn)類,主要是用于實(shí)現(xiàn)或擴(kuò)展clone方法的類。

原型模式UML類圖

什么是單例模式與原型模式

原型模式

Prototype

public abstract class PrototypePhone implements Cloneable {
    private String cpu;
    private int price;

    @Override
    public  Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
    
    //省略構(gòu)造函數(shù),get,set方法

}

Concrete Prototype

public class ConcretePrototypeOnePlus extends PrototypePhone {
    public ConcretePrototypeOnePlus(String cpu, int price) {
        super(cpu, price);
        System.out.println("調(diào)用了構(gòu)造函數(shù)");
    }

    @Override
    public Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
}

Client

public class Client {
    public static void main(String[] args) throws CloneNotSupportedException {
        PrototypePhone phone = new ConcretePrototypeOnePlus("865", 3999);
        System.out.println("原型:" + phone);
        for (int i = 0; i < 100; i++) {
            System.out.println("生產(chǎn)第" + (i + 1) + "臺(tái)手機(jī):" + phone.clone());
        }
    }
}

運(yùn)行的話就會(huì)發(fā)現(xiàn)構(gòu)建的手機(jī)只通過(guò)了一次構(gòu)造函數(shù),其它的使用phone.clone() 也能同樣構(gòu)造出手機(jī)實(shí)例對(duì)象。

到此,相信大家對(duì)“什么是單例模式與原型模式”有了更深的了解,不妨來(lái)實(shí)際操作一番吧!這里是億速云網(wǎng)站,更多相關(guān)內(nèi)容可以進(jìn)入相關(guān)頻道進(jìn)行查詢,關(guān)注我們,繼續(xù)學(xué)習(xí)!

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI