COM可以用vb, java, C++語言進行編寫, 它只關心組件的功能,與語言無關。可以把組件編譯成dll的格式或者exe格式。
COM的魯棒性----可以對com組件進行升級,使舊的程序仍然能夠運行,而新的程序可以利用組件的新特性。
COM的位置透明性------客戶機不需要知道組件的存放的位置
COM也有面向對象的特性----封裝 繼承 多態
組件需要提供接口給外部使用--------------------------所以它有一個可愛的名字: 服務器(server)
而使用組件的軟件實體-----------被迫只能喊爲: 客戶機(client)
COM的主要工作是解決接口的實現和使用等問題
這是C++的對外接口
class IMath
{
virtual int Add(int a, int b) = 0;
virtual int Subtract (int a, int b) = 0;
};
用戶可以使用它的接口來實現自己的代碼
COM也是和它差不多的,他們之間的其他差異在於:
1----COM 的語言無關性
2----COM的位置透明性
#include <string> #include <iostream> class Fruit { public: virtual void Draw(){} private: std::string m_strcolor; }; class Apple : public Fruit { virtual void Draw() { std::cout << "I am an apple \n"; } }; class GrannySmith : public Apple { virtual void Draw() { std::cout << "I am a Granny smith Apple\n"; } }; class banana : public Fruit { virtual void Draw() { std::cout << "I am an bananana \n"; } }; class orange : public Fruit { virtual void Draw() { std::cout << "I am an orange \n"; } }; int main () { Fruit* f[5]; f[0] = new Apple; f[1] = new GrannySmith; f[2] = new banana; f[3] = new orange; f[4] = new orange; for (int i =0; i < 5; i++) { f[i]->Draw(); } return 0; }
輸出結果:
I am an apple
I am a Granny smith Apple
I am an bananana
I am an orange
I am an orange
上面就是C++的一個簡單的多態例子。這裏利用虛函數和動態綁定
如果你使 Fruit中的虛函數Draw,變成純虛函數。則這個類就變爲了抽象類,那麼派生類必須實現它
virtual void Draw() = 0;
C++是使用虛表(vtable)來實現動態綁定的,COM也是使用C++中的虛表結構來建立組件的接口。因爲虛表是一個包含函數地址的數組。
因爲COM使用了一個vtable指針,所以COM接口中只能提供方法。
//下一章 :既然如此相似, 那麼如何從一個C++的類轉變到COM組件