1、有一个工厂,专门生产不同品牌的汽车。当有人需要从此工厂提货的时候,只需要告诉他,要什么品牌的,就可以了,并不关心这些车是怎么生产出来的。
2、以上方式,如果增加品牌的时候,也要修改工厂,有点麻烦。于是,把工厂也抽象了。
1的类图与实现:
首先,是通用的车
1 ///
2 /// @file Car.h
3 /// @author marrs(chenchengxi993@gmail.com)
4 /// @date 2017-08-12 20:10:31
5 ///
6
7 #ifndef __CAR_H__
8 #define __CAR_H__
9
10 #include <iostream>
11
12 namespace marrs{
13
14 using std::cout;
15 using std::cerr;
16 using std::endl;
17
18 class Car
19 {
20 public:
21 Car() : b_IsRunning(0){}
22 virtual ~Car(){};
23 public:
24 virtual void Run() = 0;
25 virtual void Stop() = 0;
26 protected:
27 bool b_IsRunning;
28 };
29
30 }
31
32 #endif //__CAR_H__
然后是不同品牌的车,继承自Car
1 ///
2 /// @file Benz.h
3 /// @author marrs(chenchengxi993@gmail.com)
4 /// @date 2017-08-12 20:20:54
5 ///
6
7 #ifndef __BENZ_H__
8 #define __BENZ_H__
9
10 #include "Car.h"
11
12 namespace marrs{
13
14 class Benz
15 : public Car
16 {
17 public:
18 ~Benz(){}
19 public:
20 void Run();
21 void Stop();
22 };
23
24 }
25
26 #endif //__BENZ_H__
1 ///
2 /// @file Benz.cc
3 /// @author marrs(chenchengxi993@gmail.com)
4 /// @date 2017-08-12 20:21:54
5 ///
6
7 #include "Benz.h"
8
9 namespace marrs{
10
11 void Benz::Run()
12 {
13 if (b_IsRunning)
14 {
15 cerr << "Benz is running!" << endl;
16 }
17
18 cout << "Benz is going to running!" << endl;
19 b_IsRunning = true;
20 }
21
22 void Benz::Stop()
23 {
24 if (!b_IsRunning)
25 {
26 cerr << "Benz isn't running..." << endl;
27 }
28
29 cout << "Benz is going to stopping!" << endl;
30 b_IsRunning = false;
31 }
32
33 }
1 ///
2 /// @file Audi.h
3 /// @author marrs(chenchengxi993@gmail.com)
4 /// @date 2017-08-12 20:20:54
5 ///
6
7 #ifndef __AUDI_H__
8 #define __AUDI_H__
9
10 #include "Car.h"
11
12 namespace marrs{
13
14 class Audi
15 : public Car
16 {
17 public:
18 ~Audi(){}
19 public:
20 void Run();
21 void Stop();
22 };
23
24 }
25
26 #endif//__AUDI_H__
1 ///
2 /// @file Audi.cc
3 /// @author marrs(chenchengxi993@gmail.com)
4 /// @date 2017-08-12 20:21:54
5 ///
6
7 #include "Audi.h"
8
9 namespace marrs{
10
11 void Audi::Run()
12 {
13 if (b_IsRunning)
14 {
15 cerr << "Audi is running!" << endl;
16 }
17
18 cout << "Audi is going to running!" << endl;
19 b_IsRunning = true;
20 }
21
22 void Audi::Stop()
23 {
24 if (!b_IsRunning)
25 {
26 cerr << "Audi isn't running..." << endl;
27 }
28
29 cout << "Audi is going to stopping!" << endl;
30 b_IsRunning = false;
31 }
32
33 }
1 ///
2 /// @file Lamborghini.h
3 /// @author marrs(chenchengxi993@gmail.com)
4 /// @date 2017-08-12 20:20:54
5 ///
6
7 #ifndef __LAMBORGHINI_H__
8 #define __LAMBORGHINI_H__
9
10 #include "Car.h"
11
12 namespace marrs{
13
14 class Lamborghini
15 : public Car
16 {
17 public:
18 ~Lamborghini(){}
19 public:
20 void Run();
21 void Stop();
22 };
23
24 }
25
26 #endif//__LAMBORGHINI_H__
1 ///
2 /// @file Lamborghini.cc
3 /// @author marrs(chenchengxi993@gmail.com)
4 /// @date 2017-08-12 20:21:54
5 ///
6
7 #include "Lamborghini.h"
8
9 namespace marrs{
10
11 void Lamborghini::Run()
12 {
13 if (b_IsRunning)
14 {
15 cerr << "Lamborghini is ru