栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

创建型模式-单例

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

创建型模式-单例

谈起:设计模式的六大原则感觉太书面了,可以从理解上在简单些:

1、功能模块独立
2、高扩展低耦合
3、抽象性复用性

整理这些设计模式的目的:从简单的代码中体会每个设计模式的灵魂所在。

偶然发现了一个对设计模式介绍的简单明了的网站:
http://c.biancheng.net/view/1317.html

单例模式:最简单和常用的一种,仅且只能有一个对象实例 (全局的)从而实现属性共享。因为我们使用Js/Ts去书写的所以就不考虑多线程的问题了,有兴趣可以搜索一下C++,Java的设计模式。
优点:… … …
缺点:… … …

一、比较常用的两种写法懒汉/饿汉;根据代码可以看出只是在创建对象的时机不同而已,没有什么太多的区别使用哪种方式都可以,我个人习惯懒汉模式。

//懒汉模式
class Singleton {
    private static instance: Singleton = null;
    private constructor() { }
    public static GetInstance(): Singleton {
        if (!this.instance) {
            this.instance = new Singleton();
        }
        return this.instance;
    } 
}

//饿汉模式
class Singleton {
    private constructor() { }
    private static instance: Singleton = new Singleton();
    public static GetInstance(): Singleton {
        return this.instance;
    }
}

//其他脚本使用的时候
Single.GetInstance().xx

二、上面两种方式书写比较直观,但是工程比较大的情况下就感觉每次都这么写比较麻烦,所以有了第二种单例模板

class Singleton{
    private static instance: any = null;
    public static GetInstance(c: { new(): T }): T
    {
        if (this.instance == null)
        {
            this.instance = new c();
        }
        return this.instance;
    }
}
//继承单例模板
class SoundManager extends Singleton
{
    public test() { }
}
//其他脚本使用
SoundManager.GetInstance(SoundManager).test();
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/315090.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号