利用外观模式模拟股民炒股 C++

来源:互联网 发布:linux查看文件大小m 编辑:程序博客网 时间:2024/06/11 21:28

说下对外观模式的理解
外观模式, 为子系统中的一组接口提供了一个一致的界面, 此模式定义了一个高级接口, 这个接口使得这个子系统更加容易使用。
利用外观模式, 客户可以完全不用知道子系统的内部实现, 只要调用外观模式对外提供的接口即可。他完美的体现了依赖倒转原则和迪米特法则的思想。
通常可以用来做分层结构, 在层与层之间利用外观模式, 减低层之间的耦合度。减小因不断重构演化使程序越来越复杂。 他还可以用来维护一些高度复杂, 设计粗糙的遗留代码。

为便于理解, 贴一张图:
这里写图片描述

uml图:
这里写图片描述

直接上代码:
mainstock.h

#ifndef _MAINSTOCK_H_#define _MAINSTOCK_H_#include <iostream>using std::cout;using std::endl;/************************************************************************//*                各种杂乱的股票类                                      *//************************************************************************/class CStock1{public:    void sell(){ cout << "sell the stock1" << endl; }    void buy(){ cout << "buy the stock1" << endl; }};class CStock2{public:    void sell(){ cout << "sell the stock2" << endl; }    void buy(){ cout << "buy the stock2" << endl; }};class CStock3{public:    void sell(){ cout << "sell the stock3" << endl; }    void buy(){ cout << "buy the stock3" << endl; }};class CStock4{public:    void sell(){ cout << "sell the stock4" << endl; }    void buy(){ cout << "buy the stock4" << endl; }};#endif // _MAINSTOCK_H_

funds.h

#ifndef _FUNDS_H_#define _FUNDS_H_#include "MainStocks.h"/************************************************************************//* 基金类, 用来提供基础类与客户类交互的方式                            *//************************************************************************/class CFunds{public:    void buyFund1(){        stock1.buy();        stock2.buy();        stock3.buy();    }    void buyFund2(){        stock2.buy();        stock4.buy();    }private:    CStock1 stock1;    CStock2 stock2;    CStock3 stock3;    CStock4 stock4;};#endif // _FUNDS_H_

main.cpp

#include <iostream>#include "funds.h"using namespace std;int main(){    CFunds fund;    fund.buyFund1();    fund.buyFund2();    system("pause");    return 0;}
0 0