shuidichuanshi

UML图:

 

c++代码:

#include <stdio.h>
#include <stdlib.h>
#include <iostream>

using namespace std;

//CPU
class CPU
{
public:
    virtual void show() = 0;
};

class macCPU : public CPU
{
public:
    void show()
    {
        cout << "show mac cpu" << endl;
    }
};

class pcCPU : public CPU
{
public:
    void show()
    {
        cout << "show pc cpu" << endl;
    }
};
//内存
class Ram
{
public:
    virtual void show() = 0;
};

class macRam : public Ram
{
public:
    void show()
    {
        cout << "show mac ram" << endl;
    }
};

class pcRam : public Ram
{
public:
    void show()
    {
        cout << "show pc ram" << endl;
    }
};
//抽象工厂
class AbstractFactory
{
public:
    virtual CPU *CreateCPU() = 0;
    virtual Ram *CreateRam() = 0;
};
//具体的工厂
//mac工厂
class MacFactory : public AbstractFactory
{
public:
    CPU *CreateCPU()
    {
        return new macCPU();
    }
    Ram *CreateRam()
    {
        return new macRam();
    }
};
//pc工厂
class PCFactory : public AbstractFactory
{
public:
    CPU *CreateCPU()
    {
        return new pcCPU();
    }
    Ram *CreateRam()
    {
        return new pcRam();
    }
};

客户端测试:

#include "stdafx.h"
#include "AbstractFactory.h"

int _tmain(int argc, _TCHAR* argv[])
{
    AbstractFactory *macFactory = new MacFactory();
    AbstractFactory *pcFactory = new PCFactory();

    CPU *cpu1 = macFactory->CreateCPU();
    Ram *ram1 = macFactory->CreateRam();
    cpu1->show();
    ram1->show();

    CPU *cpu2 = pcFactory->CreateCPU();
    Ram *ram2 = pcFactory->CreateRam();
    cpu2->show();
    ram2->show();

    delete cpu1, ram2, cpu2, ram2;
    delete macFactory, pcFactory;

    getchar();
    return 0;
}

 

分类:

技术点:

相关文章: