设计模式复习-抽象工厂模式
设计模式复习-抽象工厂模式
有两种硬件,PC和Phone,有两种系统,Windows和Linux,现在假设PC和Phone上全都能安装这两个系统,并且将来硬件不会在变化,但是系统可能需要扩展,比如扩展一个Android系统,处理这样的问题,尽量满足OCP。
//FactoryMode.h
#pragma once#includeusing namespace std;class CinterfaceOS {public:virtual void StartOs() = 0;virtual void CloseOs() = 0;};class CWindows : public CinterfaceOS {public:void StartOs() {cout << "Start Windows OS" << endl;}void CloseOs() {cout << "Close Windows OS" << endl;}};class CLinux : public CinterfaceOS {public:void StartOs() {cout << "Start Linux OS" << endl;}void CloseOs() {cout << "Close Linux OS" << endl;}};class CWindowsPC : public CWindows {public:void StartOs() {cout << "StartWindowsPC:";CWindows::StartOs();}void CloseOs() {cout << "CloseWindowsPC:";CWindows::CloseOs();}};class CWindowsPhone : public CWindows {public:void StartOs() {cout << "StartWindowsPhone:";CWindows::StartOs();}void CloseOs() {cout << "CloseWindowsPhone:";CWindows::CloseOs();}};class CLinuxPC : public CLinux {public:void StartOs() {cout << "StartLinuxPC:";CLinux::StartOs();}void CloseOs() {cout << "CloseLinuxPC:";CLinux::CloseOs();}};class CLinuxPhone : public CLinux {public:void StartOs() {cout << "StartLinuxPhone:";CLinux::StartOs();}void CloseOs() {cout << "CloseLinuxPhone:";CLinux::CloseOs();}};class CInterfaceFactory {public:virtual CinterfaceOS * CreatePcOs() = 0;virtual CinterfaceOS * CreatePhoneOs() = 0;};class CCreateFactoryWindows : public CInterfaceFactory {CinterfaceOS * CreatePcOs() {return new CWindowsPC();}CinterfaceOS * CreatePhoneOs() {return new CWindowsPhone();}};class CCreateFactoryLinux : public CInterfaceFactory {CinterfaceOS * CreatePcOs() {return new CLinuxPC();}CinterfaceOS * CreatePhoneOs() {return new CLinuxPhone();}};#include "stdafx.h"#include "FactoryMode.h"#include using namespace std;int main() {CInterfaceFactory *pHashFactoryWindows = NULL;CinterfaceOS *pHashOsWindowsPC = NULL;CinterfaceOS *pHashOsWindowsPhone = NULL;CInterfaceFactory *pHashFactoryLinux = NULL;CinterfaceOS *pHashOsLinuxPC = NULL;CinterfaceOS *pHashOsLinuxPhone = NULL;pHashFactoryWindows = new CCreateFactoryWindows();pHashOsWindowsPC = pHashFactoryWindows->CreatePcOs();pHashOsWindowsPhone = pHashFactoryWindows->CreatePhoneOs();pHashFactoryLinux = new CCreateFactoryLinux();pHashOsLinuxPC = pHashFactoryLinux->CreatePcOs();pHashOsLinuxPhone = pHashFactoryLinux->CreatePhoneOs();pHashOsWindowsPC->StartOs();pHashOsWindowsPC->CloseOs();pHashOsWindowsPhone->StartOs();pHashOsWindowsPhone->CloseOs();pHashOsLinuxPC->StartOs();pHashOsLinuxPC->CloseOs();pHashOsLinuxPhone->StartOs();pHashOsLinuxPhone->CloseOs();delete pHashOsWindowsPC;delete pHashOsWindowsPhone;delete pHashFactoryWindows;delete pHashOsLinuxPC;delete pHashOsLinuxPhone;delete pHashFactoryLinux;//getchar();return 0;}
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
暂时没有评论,来抢沙发吧~