设计模式

单列模式

懒汉式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Singleton {
private:
Singleton() {

}
public:
static Singleton *GetSingleton() {
if (single == NULL) {
return single = new Singleton;
}
return single;
}
private:
static Singleton* single;
};
Singleton* Singleton::single = NULL;
int main(int argc, const char * argv[]) {
Singleton* s1 = Singleton::GetSingleton();
Singleton* s2 = Singleton::GetSingleton();
if (s1 == s2) {
cout << "s1 == s2" << endl;
} else {
cout << "s1 != s2" << endl;
}
return 0;
}

恶汉式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Singleton {
private:
Singleton() {

}
public:
static Singleton *GetSingleton() {
// if (single == NULL) {
// return single = new Singleton;
// }
return single;
}
private:
static Singleton* single;
};
Singleton* Singleton::single = new Singleton;
int main(int argc, const char * argv[]) {

Singleton* s1 = Singleton::GetSingleton();
Singleton* s2 = Singleton::GetSingleton();
if (s1 == s2) {
cout << "s1 == s2" << endl;
} else {
cout << "s1 != s2" << endl;
}
return 0;
}

工厂模式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81

class Fruit {
public:
virtual void sayName() {
cout << "Fruit" << endl;
}
};

class SouthBanana : public Fruit {
public:
virtual void sayName() {
cout << "SouthBanana" << endl;
}
};

class SouthApple : public Fruit {
public:
virtual void sayName() {
cout << "SouthApple" << endl;
}
};

class NorthBanana : public Fruit {
public:
virtual void sayName() {
cout << "NorthBanana" << endl;
}
};

class NorthApple : public Fruit {
public:
virtual void sayName() {
cout << "NorthApple" << endl;
}
};

class FruitFactory {
public:
virtual Fruit* getBanana() {
cout << "FruitFactory:getBanana " << endl;
return NULL;
}
virtual Fruit* getApple() {
cout << "FruitFactory:getApple " << endl;
return NULL;
}
};

class SouthFactory : public FruitFactory {
public:
virtual Fruit* getBanana() {
return new SouthBanana;
}
virtual Fruit* getApple() {
return new SouthApple;
}
};

class NorthFactory : public FruitFactory {
public:
virtual Fruit* getBanana() {
return new NorthBanana;
}
virtual Fruit* getApple() {
return new NorthApple;
}
};

int main(int argc, const char * argv[]) {
FruitFactory *ff = NULL;
Fruit* fruit = NULL;

ff = new SouthFactory;
fruit = ff->getBanana();
fruit->sayName();

delete fruit;
delete ff;

return 0;
}