六狼论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

新浪微博账号登陆

只需一步,快速开始

搜索
查看: 38|回复: 0

设计模式之单件模式

[复制链接]

升级  51%

109

主题

109

主题

109

主题

举人

Rank: 3Rank: 3

积分
353
 楼主| 发表于 2013-1-15 02:40:39 | 显示全部楼层 |阅读模式
1,单件(Singleton):允许一个类有且仅有一个实例.
#include <iostream>#include <stdexcept>using namespace std;class Singleton{    //私有    Singleton(int x):i(x){}    Singleton(const Singleton&);    Singleton& operator=(Singleton&);    int i;public:    //返回引用    //一个类中的任何static成员都可表示一个单件    static Singleton& instance()    {        static Singleton s(43);        return s;    }    void setVal(int x){ i=x; }    int getVal(){ return i; }};int main(){    Singleton& s=Singleton::instance(); //这里必须声明为引用    cout<<s.getVal()<<endl;    s.setVal(15);    cout<<s.getVal()<<endl;    return 0;}

2,信使(messenger):将消息封装到一个对象中到处传递.
#include <iostream>using namespace std;class Point{public:    int x,y,z;    Point(int a,int b,int c):x(a),y(b),z(c){}    Point(const Point& p):x(p.x),y(p.y),z(p.z){}    Point& operator=(const Point& rhs)    {        this->x=rhs.x;        this->y=rhs.y;        this->z=rhs.z;        return *this;    }    friend ostream& operator<<(ostream& os,const Point& p)    {        return os<<p.x<<" "<<p.y<<" "<<p.z;    }};class Space{public:    //p作为信使使用    static Point& translate(Point p,int i)    {        p.x+=i;        p.y+=i;        p.z+=i;        return p;    }};int main(){    Point p1(3,4,5);    cout<<p1<<endl;    Point p2=Space::translate(p1,3);    cout<<p2<<endl;    return 0;}
3,"奇特的递归模板模式"实现单件.
#include <iostream>using namespace std;template<class T>class Singleton{    Singleton(const Singleton&);    Singleton& operator=(const Singleton&);protected:    Singleton(){}    virtual ~Singleton(){}public:    static T& instance()    {        static T s;        return s;    }};//注意这里诡异的派生//Singleton<MyClass>之所以可以被编译器实例化,是因为它不依赖于类MyClass的大小.//只是在Singleton<MyClass>::instance()第一次被调用时,才需要知道类MyClass的大小.//此时,编译器已经知道MyClass的大小了.class MyClass:public Singleton<MyClass>{    int i;protected:    //声明Singleton<MyClass>为友元    friend class Singleton<MyClass>;    //构造函数为私有或保护    MyClass(){ i=43; }public:    void setVal(int x){ i=x; }    int getVal(){ return i; }};int main(){    MyClass& m=MyClass::instance();    cout<<m.getVal()<<endl;    m.setVal(15);    cout<<m.getVal()<<endl;    return 0;}

4,延时实例化(5个文件)
知道第一次调用函数logfile时,才进行实例化.
logfile.h
#ifndef LOGFILE_H_INCLUDED#define LOGFILE_H_INCLUDED#include<fstream>std::ofstream& logfile();#endif // LOGFILE_H_INCLUDED
logfile.cpp
#include "logfile.h"//必须不是内联的std::ofstream& logfile(){    //这里是核心    static std::ofstream log("log.txt");    return log;}
uselog1.h
#ifndef USELOG1_H_INCLUDED#define USELOG1_H_INCLUDED#include "logfile.h"void f();#endif // USELOG1_H_INCLUDED
uselog1.cpp
#include "uselog1.h"void f(){    logfile()<<__FILE__<<std::endl;}
main.cpp
#include "logfile.h"#include "uselog1.h"using namespace std;void g(){    logfile()<<__FILE__<<endl;}int main(){    f();    g();    return 0;}
您需要登录后才可以回帖 登录 | 立即注册 新浪微博账号登陆

本版积分规则

快速回复 返回顶部 返回列表