您的位置:首页 > 其它

类只能实例化一次

2009-09-24 08:46 127 查看
昨天听到同学讨论的一个问题,问题是:类如何实例化一次。

上网查了下,查到了23种设计模式的问题。

创建型:
1. 单件模式(Singleton Pattern)
2. 抽象工厂(Abstract Factory)
3. 建造者模式(Builder)
4. 工厂方法模式(Factory Method)
5. 原型模式(Prototype)
结构型:
6. 适配器模式(Adapter Pattern)
7. 桥接模式(Bridge Pattern)
8. 装饰模式(Decorator Pattern)
9. 组合模式(Composite Pattern)
10. 外观模式(Facade Pattern)
11. 享元模式(Flyweight Pattern)
12. 代理模式(Proxy Pattern)
13. 模板方法(Template Method)
14. 命令模式(Command Pattern)
15. 迭代器模式(Iterator Pattern)
行为型:
16. 观察者模式(Observer Pattern)
17. 解释器模式(Interpreter Pattern)
18. 中介者模式(Mediator Pattern)
19. 职责链模式(Chain of Responsibility Pattern)
20. 备忘录模式(Memento Pattern)
21. 策略模式(Strategy Pattern)
22. 访问者模式(Visitor Pattern)
23. 状态模式(State Pattern)

而类的只能实例化一次,是其中的一种,单件模式的一种方法。

我一开始只认为,实例化一次,是只能定义一次而已。而事实证明是错的。正确的说,是内存中,只能有一个这样的实例。结合网上的例子,加了点代码,证明上面的想法。

#include<iostream>
using namespace std;

class Singleton
{
public:
static Singleton* Instance();
int b;
protected:
Singleton(){};
private:
static Singleton* _instance;
};

Singleton* Singleton::_instance = 0;

Singleton* Singleton::Instance () {
if (_instance == 0) {
_instance = new Singleton;
}
return _instance;
}

int main()
{
Singleton *a=Singleton::Instance();
a->b=10;
Singleton *b=Singleton::Instance();
cout<<b->b<<endl;
}

上面输出的b->b为10。。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: