计算机包括内存(RAM)、CPU等硬件设备,根据图示的“产品等级结构-产品族”示意图,使用抽象工厂模式实现计算机设备创建过程并绘制相应的类图,并用面向对象语言编程模拟。

类图:
在这里插入图片描述

  • Java实现:
package cn.xiaov.abstractfactory.computer;

public class Computer {
    public static void main(String[] args) {
        AbstractFactory afPc=new PcFactory();
        afPc.getCPU().show();
        afPc.getRAM().show();

        AbstractFactory afMac = new MacFactory();
        afMac.getCPU().show();
        afMac.getRAM().show();
    }
}

interface CPU {
    void show();
}

class PcCPU implements CPU {

    @Override
    public void show() {
        System.out.println("PC的CPU");
    }
}

class MacCpu implements CPU {

    @Override
    public void show() {
        System.out.println("Mac的CPU");
    }
}

interface RAM {
    void show();
}

class PcRAM implements RAM {

    @Override
    public void show() {
        System.out.println("PC的RAM");
    }
}

class MacRAM implements RAM {

    @Override
    public void show() {
        System.out.println("Mac的RAM");
    }
}

interface AbstractFactory{
    RAM getRAM();
    CPU getCPU();
}

class PcFactory implements AbstractFactory{

    @Override
    public RAM getRAM() {
        return new PcRAM();
    }

    @Override
    public CPU getCPU() {
        return new PcCPU();
    }
}
class MacFactory implements AbstractFactory{
    @Override
    public RAM getRAM() {
        return new MacRAM();
    }

    @Override
    public CPU getCPU() {
        return new MacCpu();
    }
}

运行截图:
在这里插入图片描述

  • c++实现
#include<iostream>
using namespace std;

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

class PcCPU :public CPU {
	void show() {
		cout << "PC的CPU" << endl;
	}
};

class MacCPU :public CPU {
	void show() {
		cout << "Mac的CPU" << endl;
	}
};

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

class PcRAM :public RAM {
	void show() {
		cout << "PC的RAM" << endl;
	}
};

class MacRAM :public RAM {
	void show() {
		cout << "Mac的RAM" << endl;
	}
};

class AbstractFactory {
public:
	virtual RAM* getRAM() = 0;
	virtual CPU* getCPU() = 0;
};

class PcFactory :public AbstractFactory {
	RAM* getRAM() {
		return new PcRAM();
	}
	CPU* getCPU() {
		return new PcCPU();
	}
};

class MacFactory :public AbstractFactory {
	RAM* getRAM() {
		return new MacRAM();
	}
	CPU* getCPU() {
		return new MacCPU();
	}
};

int main() {
	AbstractFactory* afPc = new PcFactory();
	afPc->getCPU()->show();
	afPc->getRAM()->show();

	AbstractFactory* afMac = new MacFactory();
	afMac->getCPU()->show();
	afMac->getRAM()->show();

	return 0;
}

运行截图:
在这里插入图片描述

Logo

开放原子开发者工作坊旨在鼓励更多人参与开源活动,与志同道合的开发者们相互交流开发经验、分享开发心得、获取前沿技术趋势。工作坊有多种形式的开发者活动,如meetup、训练营等,主打技术交流,干货满满,真诚地邀请各位开发者共同参与!

更多推荐