Online Ghost Game Development II-Design business object and object responsibility Division (3)

Source: Internet
Author: User

"Memories are always cruel"-in the " design business objects and objects of responsibility Division (2)", the old version of the code is analyzed, but also found a lot of smelly road, this article will record how I build a new version of the business object division of responsibility.

First, review the design pattern

The original way of self-study design mode is: From "Big talk design Mode" began (made notes), to the Gof "design mode", and then to the hard users of the summary of the blog (only see C # may be some limitations ~). Since then, whenever I need to update the code, or I do not remember the 23 classic design patterns, I will go back to my notes, mainly see: The purpose of the model, the application scenario, the fastest speed in the brain playback. In the review at the same time, will not consciously think that the design pattern may be resolved to update some problems in the project, and then immediately read the code in paragraph (2) analysis, and on the draft board (bought a whiteboard when the draft paper) UML class diagram simple design, and in mind the sample code. I think it's like, and should be, like the actions that need to be done in the future, to be repetitive and skillful.

Writing here, I felt the need to share a note in a sentence summed up in the 23 design pattern part, so wrote: a sentence of the design mode, I believe must be a slot full:)

After review, the initial thought may be able to use the pattern has:

Created type: Singleton (Setting), candidate: factory;

Structural type: decoration (dealing with the relationship between roles), Candidate: bridging, agent;

Behavioral: Observer (timed update), mediator (by game as the mediator of each participant), state (change of voting state, may be over-designed), candidate: visitor;

Second, optimize the game process

(1) Old version: After entry has the Spectator/Registration button for the user to choose, table class is responsible for maintaining the list of all people, exit spectator/registration will continue to change the class;

Optimization: After entering the spectator does not need to do anything, but the applicant needs to click on the "Seat" button-more in line with the reality of the scene; Table class no longer maintains the spectator list-because the table game table only need to control who participate in the game, what the spectator name in the entire game process has not contributed to the beginning of the game Seating (i.e. registration and spectator) will not have new class generation-because the identity of a civilian, an idiot, or a ghost should be generated only after the game has started, rather than being identified at the beginning, and thus avoiding the problem of complex conversions between classes in (2).

(2) Old version: Vote not done

Optimization: Increased voting by Addballot ()-isvoteend () whether the poll is over--roll () recount, three sections. That is: When the polling session, whenever a participant points to vote for the person or abstain, the voting manager will check whether it is over, if not end, then continue to receive the vote, if it has ended, start recount. Very well understood ~

III. Division of Object Responsibility and object collaboration sequence

This is one of the most important sections of this series: This section is continually reviewed during subsequent code implementations, and even the section can be further optimized and updated.

This section uses UML2.0 as a notation, using the rational rose tool to describe the relationships between key business classes from class diagrams, Sequence diagrams , and how these classes distribute messages and collaborate with each other in the game's main process.

(1) First look at the class diagram

Class Diagram

It's not complicated, it also omits some of the association relationships (such as ghost can be directly associated with Speakmanager, Votemanager, to solve the first round of the ghost discussion in the beginning of the problem), only to show the main relationship, we first from the previous version of the class began to say:

Old version of the 7 classes: Table, Game, Subject, Setting, audience, civilian, Ghost, in addition to audience, others are used to write.

Follow the game order:

table: A game table that is created by a single-instance mode when a game program is started, and maintains a games class with the Playermanager class inside.

Why is there no way? Of course there are, but now it belongs to the preliminary design phase, as mentioned above, these class diagram, sequence diagram, even the game process can be found in the subsequent code implementation of unreasonable, then back to change (I will return to the corresponding article to modify, specifically write a log of this series-to record the key modification behavior).

Playermanager: One of the bad smells of the old table class is that it is not only responsible for notifying the game class to start games, but also for maintaining the number of desktops, checking whether to start, and separating these unnecessary responsibilities here. The new Playermanager class, which is dedicated to maintaining the number of people, is visible by set, delete, and get on the player. The key attribute is the maintenance of a 9 member string array, NameArray, responsible for determining the seat list before the game starts. To list the order. After the game starts and assigns a role, it maintains the 9-member player array instead of Playerarray. Why use an array of arrays instead of the list in the previous version list--because it's already set. The standard number of people (can be maintained in XML, here as standard), only for the corresponding seat, and the required memory is less, class transfer between the faster and easier to store.

Setting: The only difference from the old version is that the Setting is responsible for checking whether the person seated in the registration is full isfull (), returning the Boolean type, and then reporting back to table, starting with table to game start () notification.

Game: The original a lot of responsibilities are assigned out, presumably it ~ hey! It is true that after assigning a duty there is only one start () left, and a restart of restart ()-the end of a game and the start of a time, of course, can also be responsible for recreating a game object by table, then the game is easier ~ now berthelot off a mouth with a pipe to see the big Uncle , cheerfully looked at the bottom son of a boy to work, himself just to send the number of start, the instructions, oh right, even do not say, the bottom of the younger brother himself will judge whether the game is over ~

Subject: The only difference from the old version is that the Subject is responsible for the thesaurus to get the title Getsubject (), and fill in the properties of the three stored words maintained by itself, after the outside to the word, will find him (the old version also copied a copy to the participants in the hands, This seems to be inconsistent with the reality, but in fact, it is possible to optimize the reality of the problem of manual cheating in the information flow of the advantages of the process, so need to establish a global access point, it is also considered a singleton mode creation.

player, civilian, Idiot, Ghost: The latter three inherit the player, sighted should see that the--playermanager maintained player array is the maintenance of the abstract class player, After that, if you need to propose a type of object from which to formulate, you can consider using a lambda expression, such as:list<ghost> ghostlist = PlayerManager.Player.ToList (). Where (G=>g.type (). Equals (Ghost)); --Directly hit not in VS run, there are bugs please forgive ha [Hanxiao]! In the old version, Ghost inherits from the Civilian,civilian inherited from the audience, here does not consider the Spectator class (in the code implementation part in the consideration supplement, may also add back this audience class, depends on where), And Ghost is not actually a civilian, so you should not use an inheritance relationship to express, all their similar methods should be promoted to the player abstract class to complete, as mentioned in the design pattern: non-is-a relationship, should not be represented by an inheritance relationship. So how to distinguish between civilian civilians, idiot idiots, ghost ghosts--don't forget the decorative pattern Oh ~ (Review the design patterns listed in the first section of this article, the list of possible design mode parts)

Well, the rest of the classes that are not covered are the ones that are separated from the old version of the game:

rolemanager is responsible for assigning roles,Speakmanager is responsible for managing the conversation list,Loopmanager is responsible for checking this round of speeches (including the PK statement) whether it is over, Votemanager is responsible for voting links,Deathmanager responsible for acting as executioner,Winmanager is responsible for checking whether ghosts win (ghosts do not win to continue until the ghost of the whole dead or ghost victory, So there is no need for good people to win as the end game standard).

Well, so that each class is more exclusive responsible for their own things--single responsibility principle--if real life has such a single role in the work of the good, but the social need is all-rounder, like learning computer will also be led by the leader called to move the mainframe box (analogy, analogy ~), About the work of the topic niche I also have 4 years of work experience, dare not in front of you old swim experience less insight short sermon, or take advantage of the young, while the dream is not awakened by reality, hurriedly do can bear the thing ~

(2) entry and game start sequence diagram

Enter Diagram

Sequence diagram is a thing, here believe that friends can understand one or two.

1-4. Whenever someone is seated, table will drop the person's nickname to Playermanager, Playermanager asked setting "People are all right?" "(Isfull). When someone stands up, the same thing tells Playermanager to delete a person's name, at which point Playermanager maintains a string array. If setting told Playermanager "Man Qi!" ", the message will be sent back to the table's ears, table pull out a monkey hair so a blow ah (as a painting enthusiast, must be to ignite the domestic animation" The Return of the Holy "salute! ), just pop out of a game class and start playing.

5-6. Game first to the subject, and then called to rolemanager randomly assigned to the Playermanager maintained string array role, and then put the role of the player abstract class coat, and then queued back to Playermanager. Does it feel that rolemanager is a bit like the conductor in the builder's mode--come all the way to a genius (class method), and rush to finish the task without taking a cloud. Haha, there is such a meaning, concrete can be combined with the builder model, whether it is necessary to combine the builder model, we in the code implementation part of the discussion with you.

7-8. The title and identity roles are ready, there is a system to speak to the player contestants to explain their respective identities and topics, and now enter the ghost designated the first round of speakers. Speakmanager is well-deserved as a completion of this task, which shows what the system says Systemspeak (), and then publishes the records to the foreground ShowRecord ().

(3) Ghost discussion sequence diagram

Ghost Speak Diagram

Very simple, find Speakmanager is enough ~

(4) Ghost vote (decision of first round spokesperson) sequence diagram

Ghost Vote Diagram

1-3. When the ghost votes to decide the first round of the spokesperson, the front interface will appear all the names of the button (Playermanager maintained string names array again come in handy), whenever there is a ghost to vote, Ghost object to pass the ticket to the ticket officer Votemanager, By the check-in officer, we're all done. Isvoteend (), recount roll ().

4-5. The alternative stream of events (from Ooad, the event stream is divided into the main event stream and the alternate event stream), occurs when the ghost poll results are inconsistent (someone is wrong, or the opinion is not uniform). At this time the ticket officer Votemanager will let Speakmanager help issued Imperial Decree Systemspeak (), told the front desk ShowRecord (), let ghosts hurriedly unified opinion.

6-7. When the ghost vote is unanimous, the ticket officer can be relieved, hurriedly handed the baton to Loopmanager, let it record this round began, and let Speakmanager to set allowed to speak the ghost cast out the first round of speakers. What is "allowed to speak"-if non-Speakmanager official setspeaker () players, no matter what they say are not recorded, of course, will not ShowRecord () to others, that is, "do not need out of the field", this allows who to speak the duty, Must fall to Speakmanager's body.

(5) Sequence diagram of all character players speaking

Player Speak Diagram

Unlike ghost speeches, players speak in order, and after each speaker Loopmanager will take a look at whether the round is over. I will not dwell on the specific process.

(6) Voting sequence diagram for all character players

Player Vote Diagram

1-5. Normal voting, do not repeat.

6-7. An alternative stream of events, which is used for the PK speaking session when the voting results appear with the same number of votes. Show that the voting officer will be the same ticket to Loopmanager, let it decide who first said Setloopstarter (), do not forget to tell Speakmanager allow to record his words setspeaker (), after said will return to 1-5 steps, continue to vote. Of course, as described in the series of game flow, the PK on the platform of people can not carry out their own votes, this is not reflected in the sequence diagram, in the actual code can be identified by the player's voting attributes (temporary deprivation of voting rights rule of law system bright haha).

8-9. In any case, the end of each round must be a person by the ticket officer Votemanager to death Deathmanager, and Death Execution Setplayerdie ()-The old version is the player suicide (Setdie method in the Player object), here is the executioner executions, Feel more reasonable ~ every time someone ascended to heaven, winmanager the Big Fairy will look at the table of this game (table.game) Whether the end, the end of the standard is whether the Ghost Victory Isghostwin ().

10-11. If the game is not over, then the game baton back to Votemanager hands (after all, the whole is a series of interactive polling, so that any other manager can not fit), the ticket officer will notify Loopmanager to start a new round of players to speak, Of course, do not forget to pass the Speakmanager allowed Setspeaker (), to freedom of speech oh ~

Iv. Summary of this step

At the end of this article, I would like to add a section to describe the above-mentioned pile (which I think is comparatively) clear classification and process of class responsibilities, is how the old version of the thinking is rooted in the case of the establishment. First:

In order for everyone to see the notes, I will not be abbreviated.

This is my first design considerations, you can see the upper left corner, at that time, or the use of the three-layer inherited way to handle the various roles, because the moment is not figured out, do not want to jam in this link, continue to the table and game duty separation. Looking at the lower left, the original Playermanager was just a child (Playerlist, a property), for the player abstract class that inherits and audience (but still does not solve the three-tier inheritance problem, and audience thinking is deeply rooted). After looking at the role of game in the middle of the picture and re-recruiting new employees, they were assigned their initial names as Roler, Speaker, Loopchecker, voter, Winchecker, death, Startchecker (finally through the responsibility analysis, more should be divided into the setting, only now nickname Isfull () method, from the Earth, the hidden retreat ... )。 The general order between the classes can be seen in the figure 1-13 on the right, sharp-eyed friends may see the judgment y/n logic, haha ~

This second one is for the purpose of solving the relationship problem of each role. Can see, this time has been born Playermanager class, and game class on an equal footing by table elder brother in charge. The messy notes in the picture are traces of tangled thoughts in the days of rain and Shing, and the attentive reader may have seen the enumeration role:enum, yes, I wanted the player class to inherit from the audience class, so that the three layer inherits from the two-tier inheritance, and all roles are distinguished by the role attribute of the enumeration type. But at this time due to the open closure principle (open for expansion, to modify the closed), does not apply to the increase of the enumeration-for example, if one day the game upgrade, the rule added to the role of Hua Tuo, can be a dead resurrection (a bit like killing games game upgrade), do you want to go into the enumeration to modify it? Why not add a new class to solve it, so there is the person class in the diagram, the other characters inherit from the person--Yes, so that does not go back to the old version of the three-tier inheritance? No, although the multi-tier inheritance problem has not been solved, at least one important problem has been solved: non-is-a relationship can not be inherited--civilian and Ghost is no longer an inheritance relationship! This is too important. Please remember, if just for the method call convenient, completely can be solved by template mode, no longer agent, appearance mode also become Ah, anyway inheritance relationship is really not "is a" (is-a) relationship, do not consider, otherwise may appear huge succession tree problem, Or in the same way as the old version of the parent-child class frequent conversion vortex.

The observant friends may have noticed the player's seat map that was made around the table in the upper right corner. Yes, at that time it was felt that the front-desk interface not only to be slightly optimized, but also to solve the problem of the audience class, it was similar to Texas hold ' em "Round Table + sit down button" way to replace the original registration/spectator button. Thanks to Texas hold ' em, suddenly feel audience this kind of people really do not contribute very much to the game, as if you go to Macau casino, you may only care about the opponent of the table competition is what kind of people, and do not care about the sit around stand up the bystanders (don't mind the cheat of God's cheating bystanders ah ~), even the name of the bystanders At best, we know how many people are around. (through the cookie statistics can be, and do not need immediate updating, fixed a longer time update will not affect, can save traffic).

So I think the interface should be a little bit more laid out and, by the way, straighten out the main order in the first draft diagram, so there's a third picture:

Haha, the first look at the picture to go, it seems that apart from the list of the table is no difference, OK ... I admit it's true.

The right-hand shape in the diagram, such as curly braces, arrows, is the flow arrows in the sequence diagram. is not found very rough, and even the whole process (sequence diagram) so many, how a few lines to get it: when drawing to the third picture, I feel that the chaos of thinking has been opened, responsibility division, Process optimization, object relations and other major issues have been basically solved, only a full list of rules and regulations can be the world of the drawings-that, Sketch of the idea of the link has been broken, you can enter a summary of ideas, finishing the link of the document, and then I transferred to the above section of the third class diagram, sequence diagram of the drawing process.

If you have to ask what the above three charts are all about, then I can only shoot my head casually with a meaningless name--not confined to the drawing tools in hand (rational rose or Visio or VS's modeling project), At first, can not be so neat computer software will be brain in the mind jump, chaos to the whole brain waves show, personal advice or on the draft paper, Box line, rough mark, with the fastest speed to write down what you want to realize, do not forget, software and advanced also for human Services, Believe in your own brain and grip your pen!

If you must say the order, then refer to RUP (Unified software development process), learn more about Ooad (object-oriented analysis and design), combined with solid principles (single duty, open closure, Richter replacement, interface isolation, dependency reversal) throughout the design, coding process constantly iterative review, Finally do perfect--can not help but think of my senior sketch teacher, James Zhao, Zhao teacher love painting, there is a pair of large banyan under the painting he spent many years, today fishing back to add a few pens, next year Lunar New Year happy and add a few pens, so repeatedly ...

Coder, we have to do a lot of things, even if not on the road to technology, but also to make friends, from the code to see the attitude, understand the world, do not waste once in the IT road to go .

PS: There may be readers doubt, how the results of the design does not reflect the essence of the specific design pattern? Because of the author's consideration, the design pattern can not leave the code, and the design pattern is the idea, is the proposal, but not the ultimate goal, can be considered in the design process, thinking, until the code realization link reflects its connotation and essence, even the pattern of deformation, is better than falling into the design too much.

(write for three or four hours, first post dinner, then to proofread the typos ha ~ #校对后删此行 #)

Online Ghost Game Development II-Design business object and object responsibility Division (3)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.