单例模式

作者: 周文洪 | 来源:发表于2013-08-13 17:48 被阅读646次

【风趣的解释】

Singleton Mode

最近桃花运不错,QQ上加了一个漂亮美眉,微信上加了两个漂亮美眉。加个美眉,聊聊天,反正又不花钱!她们现在都认识我了,只要她们想到那个又高又帅,姓周的小子,那就指的是我。我真是没救了,整天做白日梦...

【正式的解释】

单例模式

一种特殊的类,只有一个实例。通过单例模式可以保证系统中一个类只有一个实例而且该实例易于外界访问,从而方便对实例个数的控制并节约系统资源。

【Python版】

#-*- coding:utf-8 -*-

#这就是我,世界上独一无二
class Me(object):
    __instance = None

    def __new__(cls, *args, **kwargs):
        if not cls.__instance:
            cls.__instance = super(cls.__class__, cls).__new__(
                                 cls, *args, **kwargs)
        return cls.__instance

    def __init__(self):
        self.__name = "Mr.Zhou"
        self.__height = "120cm"
        self.__gender = "man"

    def getName(self):
        return self.__name

    def getHeight(self):
        return self.__height

    def getGender(self):
        return self.__gender

    def getIntroduction(self):
        return "Hi, I am " + self.__name + ", " + self.__height + ", and a " + self.__gender + "."

if __name__ == "__main__":
    m1 = Me()
    m2 = Me()

    print m1 == m2
    print m1.getIntroduction()

"""print out

True
Hi, I am Mr.Zhou, 120cm, and a man.
"""

【JS版】

//这就是我,世界上独一无二
function Me(){
    if(typeof Me.instance === "object"){
        return Me.instance;
    }

    this.__name = 'Mr.Zhou',
    this.__height = '120cm',
    this.__gender = 'man';

    Me.instance = this;
}

Me.prototype = {
    getName: function(){
        return this.__name;
    },
    getHeight: function(){
        return this.__height;
    },
    getGender: function(){
        return this.__gender;
    },
    getIntroduction: function(){
        return 'Hi, I am ' + this.__name + ', ' + this.__height + ', and a ' + this.__gender + '.';
    }
};


var m1 = new Me();
var m2 = new Me();

console.log(m1===m2);
console.log(m1.getIntroduction());

/*console out

true
Hi, I am Mr.Zhou, 120cm, and a man.
*/

相关文章

  • 【设计模式】单例模式

    单例模式 常用单例模式: 懒汉单例模式: 静态内部类单例模式: Android Application 中使用单例模式:

  • Android设计模式总结

    单例模式:饿汉单例模式://饿汉单例模式 懒汉单例模式: Double CheckLock(DCL)实现单例 Bu...

  • 2018-04-08php实战设计模式

    一、单例模式 单例模式是最经典的设计模式之一,到底什么是单例?单例模式适用场景是什么?单例模式如何设计?php中单...

  • 设计模式之单例模式详解

    设计模式之单例模式详解 单例模式写法大全,也许有你不知道的写法 导航 引言 什么是单例? 单例模式作用 单例模式的...

  • Telegram开源项目之单例模式

    NotificationCenter的单例模式 NotificationCenter的单例模式分析 这种单例模式是...

  • 单例模式Java篇

    单例设计模式- 饿汉式 单例设计模式 - 懒汉式 单例设计模式 - 懒汉式 - 多线程并发 单例设计模式 - 懒汉...

  • IOS单例模式的底层原理

    单例介绍 本文源码下载地址 1.什么是单例 说到单例首先要提到单例模式,因为单例模式是单例存在的目的 单例模式是一...

  • 单例

    iOS单例模式iOS之单例模式初探iOS单例详解

  • 单例模式

    单例模式1 单例模式2

  • java的单例模式

    饿汉单例模式 懒汉单例模式

网友评论

    本文标题:单例模式

    本文链接:https://www.haomeiwen.com/subject/qspftttx.html