zoukankan      html  css  js  c++  java
  • python 设计模式之 单例模式

    单例模式是做为"全局变量"的替代品出现的。所以它具有全局变量的特点:全局可见、贯穿应用程序的整个生命期,保证在程序执行中,某个类仅仅存在一个实例,所以通常不希望类中的构造函数被调用

     

    python:

     

    class Single(object):
    	instance = None	
    	#
    	def __init__(self):
    		pass
    	#
    	def getInstance(self):
    		if Single.instance == None:
    			Single.instance = Single()
    		return Single.instance
    	#
    	def printSelf(self):
    		if Single.instance != None:
    			print Single.instance
    
    s = Single()
    s1 = s.getInstance()
    s2 = s.getInstance()
    s1.printSelf()
    s2.printSelf()</span>
    

    C++:

    Single.h

    ifndef __SINGLE_H
    #define __SINGLE_H
    
    class Single
    {
    private:
    	static Single *instance;
    
    	Single();
    
    public:
    	static Single* getInstance();
    	void printSelf();
    };
    
    #endif
    


    Single.cpp

    #include "Single.h"
    #include <iostream>
    
    Single* Single::instance = NULL;
    
    Single::Single()
    {
    }
    
    Single* Single::getInstance()
    {
    	if (!instance)
    		instance = new Single;
    
    	return instance;
    }
    
    void Single::printSelf()
    {
    	if (instance)
    		std::cout << instance << std::endl;
    }
    


     

    #include "Single.h"
    
    int main()
    {
    	Single::getInstance()->printSelf();
    	Single *sin = Single::getInstance();
    	sin->printSelf();
    	return  0;
    }
    


     

     

     

  • 相关阅读:
    Django模型层进阶
    Django模型层相关
    BOM与DOM
    JavaScript入门
    HTML基础
    子查询/联合分组/all与any/视图/事务
    表的查询
    mysql的多表关系
    Mysql基本操作
    Spider_基础总结2_Requests异常
  • 原文地址:https://www.cnblogs.com/gcczhongduan/p/5078567.html
Copyright © 2011-2022 走看看