场景
当我们作为第三方开发者,需要提供库给客户使用,同时,我们又不想让用户看到我们内部的实现方法
UML
比如,我们提供给用户一个打印机类,用来实现打印服务
实现
printer.h
#ifndef _PRINT_H_
#define _PRINT_H_
#include <string>
class CPrinter
{
public:
CPrinter();
virtual ~CPrinter();
static CPrinter* createInstance(const std::string & strFile, int iPageNum);
virtual void Print() = 0;
};
#endif
printer.cpp
#include "printer.h"
#include "printerimpl.h"
#include <iostream>
CPrinter::CPrinter()
{
std::cout << "CPrinter constructor" << '
';
}
CPrinter::~CPrinter()
{
std::cout << "CPrinter deconstructor" << '
';
}
CPrinter* CPrinter::createInstance(const std::string & strFile, int iPageNum)
{
return new CPrinterImpl(strFile, iPageNum);
}
printerimpl.h
#ifndef _PRINTIMPL_H_
#define _PRINTIMPL_H_
#include "printer.h"
#include <string>
class CPrinterImpl : public CPrinter
{
public:
CPrinterImpl(const std::string & strFile, int iPageNum);
~CPrinterImpl();
void Print() override;
private:
std::string m_strFile;
int m_iPageNum;
};
#endif
printimpl.cpp
#include "printerimpl.h"
#include <iostream>
CPrinterImpl::CPrinterImpl(const std::string & strFile, int iPageNum) : m_strFile(strFile), m_iPageNum(iPageNum)
{
std::cout << "CPrinterImpl constructor" << '
';
}
CPrinterImpl::~CPrinterImpl()
{
std::cout << "CPrinterImpl deconstructor" << '
';
}
void CPrinterImpl::Print()
{
std::cout << "print server in used" << '
';
}
main.cpp
#include "printer.h"
int main()
{
CPrinter* p = CPrinter::createInstance("programming", 98);
p->Print();
delete p;
return 0;
}
Makefile
cc := g++
solib := libprinter.so
libname := -lprinter
src := printer.cpp printerimpl.cpp
obj := $(src:.cpp=.o)
target := a.out
.PHONY: all
all: build link
build: $(solib)
$(solib): $(obj)
$(cc) -shared -o $@ $^
$(obj):%.o:%.cpp
$(cc) -fPIC -c $< -o $@
link: $(target)
$(target): main.cpp $(solib)
$(cc) main.cpp -o $@ -L. $(libname)
我们可以只提供给用户一个 printer.h 头文件和 libprinter.so 库文件,不会暴露更多的细节给用户