Design Pattern-Behavior Pattern 1

Source: Internet
Author: User

Behavior mode: The Observer mode defines a one-to-many dependency, allowing multiple observer objects to listen to a topic object at the same time. when the status of this topic object changes, it notifies all observer objects so that they can automatically update themselves. the key objects in the Observer mode are the topic Subject and the Observer. A Subject can have any number of observers dependent on it. Once the status of the Subject changes, all observers can be notified. When a Subject sends a notification, it does not need to know who is its observer. That is to say, it does not need to know who is the observer. However, no specific observer knows or needs to know the existence of other observers. Application: 1. When an object needs to change other objects at the same time, and it does not know how many objects need to be changed. 2. An abstract model has two aspects: one is dependent on the other. The observer mode does the work of decoupling. Let both sides of coupling depend on abstraction, rather than on specifics. So that changes on the other side will not be affected. Textbook example: the code used by the front-end to help colleagues observe the boss is as follows: [csharp] // The notifier interface // It is generally implemented using an abstract class or an interface. it stores all references to the observer object in a aggregation, and each topic can have any number of observers. abstract topic provides an interface to add and delete the Observer object interface subject {void attach (observer Observer); void detch (observer Observer); void notify (); string subjectstate {get; set ;}}// Save the status to a specific observer object. When the internal status of a specific topic changes, send a notification to all registered observers. class boss: subject {// List of colleagues private IList <Observer> observers = new List <Observer> (); private str Ing action; // Add public void attach (Observer observer) {observers. add (observer);} // reduce public void detach (Observer observer) {observers. remove (observer);} // Notify public void Policy () {foreach (Observer o in observers) o. update () ;}// the boss State public string subjectstate {get {return action ;}set {action = value ;}}} // abstract observer // define an interface for all observers and update themselves when receiving topic notifications. abstract class Observer {protected string name; Protected subject sub; public Observer (string name, subject sub) {this. name = name; this. sub = sub;} public abstract void update ();} // the colleague who views the stock // The update Interface class stockobserver required to implement the abstract observer role: observer {public stockobserver (string name, subject sub): base (name, sub) {} public override void update () {Console. writeLine ("{0} {1} Close the stock market and continue to work", sub. subjectstate, name) ;}my understanding of observer mode is insufficient: for encapsulated classes, even if they A change produces an action, but the name of the method that generates this action is not necessarily the same. If I use the observer mode, it is very troublesome when I define an abstract observer, you need to modify the encapsulated class name and other content. Measures to solve the problem: a delegate can carry multiple methods, and all methods are called in sequence. What is important is that the methods carried by the delegate object do not need to belong to the same class. All methods carried by the delegate object must have the same prototype and form, that is, they have the same parameter list and return value type. Implementation: removed the parent class "abstract observation class" and changed the "Update" method name to the appropriate method name template. The method mode defines the skeleton of the algorithm in an operation, and delay some steps to the subclass. The template method allows the subclass to redefine certain steps of an algorithm without changing the structure of an algorithm. The Code is as follows: [csharp] class testpaper {public void TestQuestion1 () {Console. writeLine ("Yang once got it, and then gave Guo Jing, trained as Yi tianjian, Xuan tie of Tu longdao may be (). ball Milling Cast Iron B. tinplate c. high-speed alloy steel d. carbon fiber "); Console. writeLine ("Answer:" + answer1 ();} protected virtual string answer1 () {return "" ;}}// test class testpaperA copied by Student: testpaper {protected override string answer1 () {return "B" ;}}// test class testpaperB: testpaper {protected override string answe R1 () {return "c" ;}} command mode encapsulates a request as an object, so that you can parameterize the customer with different requests, queue or record request logs for requests and support unrecoverable operations. Advantages: 1. It is easier to design a command queue 2. If necessary, it is easier to log the command to log 3, allow the Requesting Party to decide whether to reject request 4, which can easily cancel and redo the request. 5. adding a new command class to the fish and fish will not affect other classes, therefore, it is easy to add a new command Class 6. The command mode splits the object requesting an operation from the object that knows how to execute an operation into a textbook instance. The code for eating a kebab is as follows: [csharp] // abstract Command, you need to determine who the "kebab" is (the interface used to declare the operation to be executed) blic abstract class Command {protected Barbecuer receiver; public Command (Barbecuer receiver) {this. extends ER = extends er;} abstract public void ExcuteCommand ();} // specific command class, execute specific behavior // roast mutton string command CIA Ss BakeMuttonCommand: Command {public BakeMuttonCommand (Barbecuer receiver): base (guest ER) {} public override void ExcuteCommand () {guest er. bakeMutton () ;}} class BakeChickenWingCommand: Command {public BakeChickenWingCommand (Barbecuer receiver): base (guest ER) {} public override void ExcuteCommand () {guest er. bakeChickenWing () ;}/// barbecue (knows how to implement and execute a request-related operation) public class Barbecuer {// Roast mutton public void BakeMutton () {Console. writeLine ("kebab");} // roast chicken wings public void BakeChickenWing () {Console. writeLine ("roast chicken wings") ;}// the Waiter (requires this Command to execute this request) public class Waiter {private IList <Command> orders = new List <Command> (); // set the order public void SetOrder (Command command) {if (command. toString () = "command mode. bakeChickenWingCommand ") {Console. writeLine ("Waiter: no chicken wings, please click another barbecue");} else {orders. add (command ); Console. writeLine ("add order:" + command. toString () + "time:" + DateTime. now. toString () ;}}// cancel the order public void CancelOrder (Command command) {orders. remove (command); Console. writeLine ("cancel order:" + command. toString () + "time:" + DateTime. now. toString ();} // execute public void Policy () {foreach (Command cmd in orders) {cmd. excuteCommand () ;}} status mode allows an object to change its behavior when its internal state changes. This object looks like it has changed its class. The State mode mainly solves the problem when the conditional expressions that control the state transition of an object are too complex. Transferring the status judgment logic to a series of classes that indicate different states can simplify the complicated judgment logic. Application: During software development, the application may perform different processing based on different situations. The most direct solution is to consider all possible situations. Then, use the if... ellse statement to determine the status for processing in different situations. However, the judgment on the complex status seems to be "Powerless ". When an object's behavior depends on its state, and it must change its behavior according to its state at runtime, you can consider using the state mode. put specific status-related behaviors into an object. Because all status-related code exists in a ConcreteState, therefore, by defining a new subclass, you can easily add new statuses and replicas. This eliminates the large number of conditional branch statements, the State mode distributes various State transfer logics to sub-classes of State to reduce the dependency between them. The status code for writing programs is as follows: [csharp] // work class public class work {private State current; public work () {current = new ForenoonState () ;} private double hour; public double Hour {get {return hour;} set {hour = value ;}} private bool finish = false; public bool TaskFinished {get {return finish ;} set {finish = value ;}} public void SetState (State s) {current = s;} public void WriteProgram () {current. writeProgram (this) ;}} public abstract class State {public abstract void WriteProgram (work w);} // public class ForenoonState in the morning: state {public override void WriteProgram (work w) {if (w. hour <12) {Console. writeLine ("Current Time: {0} Am, Times", w. hour);} else {w. setState (new NoonState (); w. writeProgram () ;}}// public class NoonState: State {public override void WriteProgram (work w) {if (w. hour <13) {Console. writeLine ("Current Time: {0}: ELE. Me lunch break", w. hour);} else {w. setState (new AfternoonState (); w. writeProgram () ;}}// public class AfternoonState: State {public override void WriteProgram (work w) {if (w. hour <17) {Console. writeLine ("the current time: {0} PM status is good, continue to work hard", w. hour);} else {w. setState (new EveningState (); w. writeProgram () ;}}// public class EveningState: State {public override void WriteProgram (work w) {if (w. taskFinished) {w. setState (new RestState (); w. writeProgram ();} else {if (w. hour <21) {Console. writeLine ("Current Time: {0} overtime, exhausted", w. hour);} else {w. setState (new SleepingState (); w. writeProgram () ;}}}// sleep State public class SleepingState: State {public override void WriteProgram (work w) {Console. writeLine ("the current time cannot be reached at {0}. I fell asleep.", w. hour) ;}}// public class RestState: State {www.2cto.com public override void WriteProgram (work w) {Console. writeLine ("Current Time: {0} is coming home from work", w. hour );}}

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.