⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 ch18.htm

📁 Why C++ is the emerging standard in software development. The steps to develop a C++ program. How
💻 HTM
📖 第 1 页 / 共 5 页
字号:
how to contact the police.</P><P>A well-designed event-driven system need not have a central coordinator. One canimagine the sensors all independently receiving and sending message objects to oneanother, setting parameters, taking readings, and monitoring the house. When a faultis detected, an <TT>Alarm</TT> object is created, which logs the problem (by sendinga message to the <TT>Log</TT> object) and takes the appropriate action.<H4 ALIGN="CENTER"><A NAME="Heading10"></A><FONT COLOR="#000077">Event Loops</FONT></H4><P>To simulate such an event-driven system, your program needs to create an eventloop. An event loop is typically an infinite loop such as <TT>while(1)</TT>, whichgets messages from the operating system (mouse clicks, keyboard presses, and so on)and dispatches them one by one, returning to the loop until an exit condition issatisfied. Listing 18.1 shows a rudimentary event loop.</P><P><A NAME="Heading11"></A><FONT SIZE="4" COLOR="#000077"><B>Listing 18.1. A simpleevent loop.</B></FONT></P><PRE><FONT COLOR="#0066FF">1:     // Listing 18.12:3:     #include &lt;iostream.h&gt;4:5:     class Condition6:     {7:     public:8:        Condition() { }9:        virtual ~Condition() {}10:       virtual void Log() = 0;11:    };12:13:    class Normal : public Condition14:    {15:    public:16:       Normal() { Log(); }17:       virtual ~Normal() {}18:       virtual void Log() { cout &lt;&lt; &quot;Logging normal conditions...\n&quot;; }19:    };20:21:    class Error : public Condition22:    {23:    public:24:       Error() {Log();}25:       virtual ~Error() {}26:       virtual void Log() { cout &lt;&lt; &quot;Logging error!\n&quot;; }27:    };28:29:    class Alarm : public Condition30:    {31:    public:32:       Alarm ();33:       virtual   ~Alarm() {}34:       virtual void Warn() { cout &lt;&lt; &quot;Warning!\n&quot;; }35:       virtual void Log() { cout &lt;&lt; &quot;General Alarm log\n&quot;; }36:       virtual void Call() = 0;37:38:    };39:40:    Alarm::Alarm()41:    {42:        Log();43:       Warn();44:    }45:    class FireAlarm : public Alarm46:    {47:    public:48:       FireAlarm(){Log();};49:       virtual ~FireAlarm() {}50:       virtual void Call() { cout&lt;&lt; &quot;Calling Fire Dept.!\n&quot;; }51:       virtual void Log() { cout &lt;&lt; &quot;Logging fire call.\n&quot;; }52:    };53:54:    int main()55:    {56:       int input;57:       int okay = 1;58:       Condition * pCondition;59:       while (okay)60:       {61:          cout &lt;&lt; &quot;(0)Quit (1)Normal (2)Fire: &quot;;62:          cin &gt;&gt; input;63:          okay = input;64:          switch (input)65:          {66:             case 0: break;67:             case 1:68:                pCondition = new Normal;69:                delete pCondition;70:                break;71:             case 2:72:                pCondition = new FireAlarm;73:                delete pCondition;74:                break;75:             default:76:                pCondition = new Error;77:                delete pCondition;78:                okay = 0;79:                break;80:          }81:       }82:     return 0;<TT>83: }</TT></FONT><FONT COLOR="#0066FF">Output: (0)Quit (1)Normal (2)Fire: 1Logging normal conditions...(0)Quit (1)Normal (2)Fire: 2General Alarm logWarning!Logging fire call.(0)Quit (1)Normal (2)Fire: 0</FONT></PRE><P><FONT COLOR="#000077"><B>Analysis:</B></FONT><B> </B>The simple loop created onlines 59-80 allows the user to enter input simulating a normal report from a sensorand a report of a fire. Note that the effect of this report is to spawn a <TT>Condition</TT>object whose constructor calls various member functions.<BR><BR>Calling virtual member functions from a constructor can cause confusing results ifyou are not mindful of the order of construction of objects. For example, when the<TT>FireAlarm</TT> object is created on line 72, the order of construction is <TT>Condition</TT>,<TT>Alarm</TT>, <TT>FireAlarm</TT>. The <TT>Alarm</TT> constructor calls <TT>Log</TT>,but it is <TT>Alarm</TT>'s <TT>Log()</TT>, not <TT>FireAlarm</TT>'s, that is invoked,despite <TT>Log()</TT> being declared virtual. This is because at the time <TT>Alarm</TT>'sconstructor runs, there is no <TT>FireAlarm</TT> object. Later, when <TT>FireAlarm</TT>itself is constructed, its constructor calls <TT>Log()</TT> again, and this time<TT>FireAlarm::Log()</TT> is called.<H3 ALIGN="CENTER"><A NAME="Heading13"></A><FONT COLOR="#000077">PostMaster</FONT></H3><P>Here's another problem on which to practice your object-oriented analysis: Youhave been hired by Acme Software, Inc., to start a new software project and to hirea team of C++ programmers to implement your program. Jim Grandiose, vice-presidentof new product development, is your new boss. He wants you to design and build PostMaster,a utility to read electronic mail from various unrelated e-mail providers. The potentialcustomer is a businessperson who uses more than one e-mail product, for example Interchange,CompuServe, Prodigy, America Online, Delphi, Internet Mail, Lotus Notes, AppleMail,cc:Mail, and so forth.</P><P>The customer will be able to &quot;teach&quot; PostMaster how to dial up or otherwiseconnect to each of the e-mail providers, and PostMaster will get the mail and thenpresent it in a uniform manner, allowing the customer to organize the mail, reply,forward letters among services, and so forth.</P><P>PostMasterProfessional, to be developed as version 2 of PostMaster, is alreadyanticipated. It will add an Administrative Assistant mode, which will allow the userto designate another person to read some or all of the mail, to handle routine correspondence,and so forth. There is also speculation in the marketing department that an artificialintelligence component might add the capability for PostMaster to pre-sort and prioritizethe mail based on subject and content keywords and associations.</P><P>Other enhancements have been talked about, including the ability to handle notonly mail but discussion groups such as Interchange discussions, CompuServe forums,Internet newsgroups, and so forth. It is obvious that Acme has great hopes for PostMaster,and you are under severe time constraints to bring it to market, though you seemto have a nearly unlimited budget.<H3 ALIGN="CENTER"><A NAME="Heading14"></A><FONT COLOR="#000077">Measure Twice, CutOnce</FONT></H3><P>You set up your office and order your equipment, and then your first order ofbusiness is to get a good specification for the product. After examining the market,you decide to recommend that development be focused on a single platform, and youset out to decide among DOS; UNIX; the Macintosh; and Windows, Windows NT, and OS/2.</P><P>You have many painful meetings with Jim Grandiose, and it becomes clear that thereis no right choice, and so you decide to separate the front end, that is the userinterface or UI, from the back end, the communications and database part. To getthings going quickly, you decide to write for DOS first, followed by Win32, the Mac,and then UNIX and OS/2.</P><P>This simple decision has enormous ramifications for your project. It quickly becomesobvious that you will need a class library or a series of libraries to handle memorymanagement, the various user interfaces, and perhaps also the communications anddatabase components.</P><P>Mr. Grandiose believes strongly that projects live or die by having one personwith a clear vision, so he asks that you do the initial architectural analysis anddesign before hiring any programmers. You set out to analyze the problem.<H3 ALIGN="CENTER"><A NAME="Heading15"></A><FONT COLOR="#000077">Divide and Conquer</FONT></H3><P>It quickly becomes obvious that you really have more than one problem to solve.You divide the project into these significant sub-projects:<DL>	<DD><B>1.</B> Communications: the ability for the software to dial into the e-mail	provider via modem, or to connect over a network.<BR>	<BR>	<B>2.</B> Database: the ability to store data and to retrieve it from disk.<BR>	<BR>	<B>3.</B> E-mail: the ability to read various e-mail formats and to write new messages	to each system.<BR>	<BR>	<B>4.</B> Editing: providing state-of-the-art editors for the creation and manipulation	of messages.<BR>	<BR>	<B>5.</B> Platform issues: the various UI issues presented by each platform (DOS,	Macintosh, and so on).<BR>	<BR>	<B>6.</B> Extensibility: planning for growth and enhancements.<BR>	<BR>	<B>7.</B> Organization and scheduling: managing the various developers and their	code interdependencies. Each group must devise and publish schedules, and then be	able to plan accordingly. Senior management and marketing need to know when the product	will be ready.</DL><P>You decide to hire a manager to handle item 7, organization and scheduling. Youthen hire senior developers to help you analyze and design, and then to manage theimplementation of the remaining areas. These senior developers will create the followingteams:<DL>	<DD><B>1.</B> Communications: responsible for both dial-up and network communications.	They deal with packets, streams, and bits, rather than with e-mail messages per se.<BR>	<BR>	<B>2.</B> Message format: responsible for converting messages from each e-mail provider	to a canonical form (PostMaster standard) and back. It is also their job to write	these messages to disk and to get them back off the disk as needed.<BR>	<BR>	<B>3.</B> Message editors: This group is responsible for the entire UI of the product,	on each platform. It is their job to ensure that the interface between the back end	and the front end of the product is sufficiently narrow that extending the product	to other platforms does not require duplication of code.</DL><H3 ALIGN="CENTER"><A NAME="Heading16"></A><FONT COLOR="#000077">Message Format</FONT></H3><P>You decide to focus on the message format first, setting aside the issues relatingto communications and user interface. These will follow once you understand morefully what it is you are dealing with. There is little sense in worrying about howto present the information to the user until you understand what information youare dealing with.</P><P>An examination of the various e-mail formats reveals that they have many thingsin common, despite their various differences. Each e-mail message has a point oforigination, a destination, and a creation date. Nearly all such messages have atitle or subject line and a body which may consist of simple text, rich text (textwith formatting), graphics, and perhaps even sound or other fancy additions. Mostsuch e-mail services also support attachments, so that users can send programs andother files.</P><P>You confirm your early decision that you will read each mail message out of itsoriginal format and into PostMaster format. This way you will only have to storeone record format, and writing to and reading from the disk will be simplified. Youalso decide to separate the &quot;header&quot; information (sender, recipient, date,title, and so on) from the body of the message. Often the user will want to scanthe headers without necessarily reading the contents of all the messages. You anticipatethat a time may come when users will want to download only the headers from the messageprovider, without getting the text at all, but for now you intend that version 1of PostMaster will always get the full message, although it may not display it tothe user.<H3 ALIGN="CENTER"><A NAME="Heading17"></A><FONT COLOR="#000077">Initial Class Design</FONT></H3><P>This analysis of the messages leads you to design the <TT>Message</TT> class.In anticipation of extending the program to non-e-mail messages, you derive <TT>EmailMessage</TT>from the abstract base <TT>Message</TT>. From <TT>EmailMessage</TT> you derive <TT>PostMasterMessage</TT>,<TT>InterchangeMessage</TT>, <TT>CISMessage</TT>, <TT>ProdigyMessage</TT>, and soforth.</P><P>Messages are a natural choice for objects in a program handling mail messages,but finding all the right objects in a complex system is the single greatest challengeof object-oriented programming. In some cases, such as with messages, the primaryobjects seem to &quot;fall out&quot; of your understanding of the problem. More often,however, you have to think long and hard about what you are trying to accomplishto find the right objects.</P><P>Don't despair. Most designs are not perfect the first time. A good starting pointis to describe the problem out loud. Make a list of all the nouns and verbs you use

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -