将cpu, disk, mem做抽象基类,camputer调用抽象基类,底层的改变不影响camputer类的实现。
#include <iostream>
#include <string>
using namespace std;
class AbsCpu
{
public:
virtual string cpu() = 0;
};
class AbsDisk
{
public:
virtual string disk() = 0;
};
class AbsMem
{
public:
virtual string mem() = 0;
};
class CpuA : public AbsCpu
{
public:
string cpu()
{
return "exe cpu A";
}
};
class CpuB : public AbsCpu
{
public:
string cpu()
{
return "exe cpu B";
}
};
class DiskA : public AbsDisk
{
public:
string disk()
{
return "exe disk A";
}
};
class DiskB : public AbsDisk
{
public:
string disk()
{
return "exe disk B";
}
};
class MemA : public AbsMem
{
public:
string mem()
{
return "exe mem A";
}
};
class MemB : public AbsMem
{
public:
string mem()
{
return "exe mem B";
}
};
class camputer
{
public:
void exeCpu(AbsCpu *pCpu)
{
cout << pCpu->cpu() << endl;
}
void exeDisk(AbsDisk * pDisk)
{
cout << pDisk->disk() << endl;
}
void exeMem(AbsMem *pMem)
{
cout << pMem->mem() << endl;
}
};
int main()
{
camputer * pCam = new camputer;
AbsCpu *pCpu = new CpuA;
AbsDisk *pDisk = new DiskB;
AbsMem *pMem = new MemA;
pCam->exeCpu(pCpu);
pCam->exeDisk(pDisk);
pCam->exeMem(pMem);
cout << "第二台电脑" << endl;
pCpu = new CpuB;
pDisk = new DiskB;
pMem = new MemA;
pCam->exeCpu(pCpu);
pCam->exeDisk(pDisk);
pCam->exeMem(pMem);
return 0;
}
更新一下:
#include <iostream>
#include <string>
using namespace std;
class AbsCpu
{
public:
virtual void cpu() = 0;
};
class AbsDisk
{
public:
virtual void disk() = 0;
};
class AbsMem
{
public:
virtual void mem() = 0;
};
class CpuA : public AbsCpu
{
public:
void cpu()
{
cout << "exe cpu A" << endl;
}
};
class CpuB : public AbsCpu
{
public:
void cpu()
{
cout << "exe cpu B" << endl;
}
};
class DiskA : public AbsDisk
{
public:
void disk()
{
cout << "exe disk A" << endl;
}
};
class DiskB : public AbsDisk
{
public:
void disk()
{
cout << "exe disk B" << endl;
}
};
class MemA : public AbsMem
{
public:
void mem()
{
cout << "exe mem A" << endl;
}
};
class MemB : public AbsMem
{
public:
void mem()
{
cout << "exe mem B" << endl;
}
};
class camputer
{
public:
camputer(AbsCpu *cpu, AbsDisk *disk, AbsMem *mem) : m_cpu(cpu),m_disk(disk),m_mem(mem)
{
}
void work()
{
m_cpu->cpu();
m_disk->disk();
m_mem->mem();
}
~camputer()
{
cout << "~camputer" << endl;
delete m_cpu;
delete m_disk;
delete m_mem;
m_cpu = NULL;
m_disk = NULL;
m_mem = NULL;
}
private:
AbsCpu *m_cpu;
AbsDisk *m_disk;
AbsMem *m_mem;
};
int main()
{
AbsCpu *pCpu = new CpuA;
AbsDisk *pDisk = new DiskB;
AbsMem *pMem = new MemA;
camputer * pCam = new camputer(pCpu, pDisk, pMem);
pCam->work();
cout << "第二台电脑" << endl;
pCpu = new CpuB;
pDisk = new DiskB;
pMem = new MemA;
pCam = new camputer(pCpu, pDisk, pMem);
pCam->work();
return 0;
}