0

这是单例模式的例子吗?如果不是,那么如果我们将此类用作记录器,可能会出现什么问题。(当然它不是一个完全弯曲的记录器)

#include <iostream>
#include <fstream>
using namespace std;


class logger
{
    private:
        static ofstream myfile;

        void openfile()
        {
            myfile.open ("example.txt");
        }
        void closefile()
        {
            myfile.close();
        }
    public:     
        void logit(string str)
        {
            if (myfile.is_open() == 1)
            {
                myfile << str << endl;
            }
            else
            {   
                openfile();
                myfile << str << endl;
            }   
        }
};

ofstream logger::myfile;
int main () 
{
    logger l;
    l.logit ("log from vod application");
    logger l2;
            l.logit ("log from guide application");

    logger l3;
    l1.logit ("log from application 3-1");
    l1.logit ("log from application 3-2");

            return 0;
}

任何讨论都会有所帮助。

德韦什

4

3 回答 3

3

不,这不是单例。

要制作单例,您必须将构造函数设为私有。您的类没有声明任何构造函数,因此,编译器将生成默认构造函数。这很糟糕,因为会有一个复制构造函数和赋值运算符,它们只是逐位复制所有成员。如果您复制已打开文件的句柄或指向已分配内存的指针并尝试使用副本进行操作,通常会发生不好的事情。

class logger {
    static logger* the_logger;
    // other private members

    logger() : the_logger(NULL)
        { /*logger construction*/} 
public:
    static logger* logger::instance(const string& filename) {
        if (the_logger == NULL) {
            the_logger = new logger(/*arguments*/);
        }
        return the_logger;
    }

    static void cleanup(void) {
        delete the_logger;
    }
    /* other public members*/
    void debug(...)
}


int main(void) 
{
    logger::instance()->debug(blah-blah-blah);
    logger::cleanup();
}

为简单起见,我跳过了与同时访问共享资源(文件描述符或输出流)相关的代码。

另外,如果我没记错的话,您的代码将无法编译,因为只能使用静态成员函数访问静态成员。

于 2013-10-29T12:08:58.747 回答
1

它不可能是单例:

  1. 您的代码中有3 个实例
  2. 该类有一个公共构造函数,它只是创建一个新实例
于 2013-10-29T12:03:05.543 回答
1

正如其他人所说,它不是单例。它是一个 Monostate:http ://c2.com/cgi/wiki?MonostatePattern ,它是相关但不同的。

于 2013-10-29T12:42:37.800 回答