设计模式5: Singleton模式
Sunday, April 27th, 2008 何时使用Singleton对象:
1. 对象有且只有一个实例
2. 对象需要Lazy Initialization
3. 没有全局访问的方法
何时使用Singleton对象:
1. 对象有且只有一个实例
2. 对象需要Lazy Initialization
3. 没有全局访问的方法
使用一个静态方法创建子类对象:
// A factory method is a static method of a class that
// returns an object of that class’ type. But unlike a
// constructor, the actual object it returns might be
// an instance of a subclass. Another advantage of a
// factory method is that it can return existing
// instances multiple times. [Mark Davis]
class Stooge {
public:
[...]
看下面的实例, 程序中需要有不同的对日期格式化的方法。
Strategy模式的思路如下:
1. 定义格式化日期的抽象接口
场景:
试想如果需要实现一个丰富的文本编辑器(Rich Text),对于每一个字符,可以用一个类来表示,记录该字符的位置,大小,字体,颜色,Unicode值等等。这是一个简单的设计,但仔细想一下,在一篇很长的文档中,同样大小或字体的字符可能会很多。如果每个字符都记录同样的信息,那势必要浪费很多空间。
解决方案: