Design Pattern-Behavior Pattern 3

Source: Internet
Author: User

Behavior mode: the Policy mode defines the algorithm family and encapsulates them separately so that they can be replaced with each other. This mode changes the algorithm and does not affect the customers who use the algorithm. Disadvantages of the simple factory model: Because the factory itself includes all the charging methods, the mall may change the discount quota and the rebate quota on a regular basis. Every maintenance or expansion of the charging method must change the factory, as a result, the code needs to be re-compiled and deployed, which is very troublesome: 1. Define a public interface of all supported algorithms 2. encapsulate all specific algorithms or actions together. 3, maintain reference to public interfaces client code is to instantiate all algorithms this mode involves three roles: Environment (Context) Role: Hold a reference to the Strategy class. Abstract Policy (Strategy) Role: This is an abstract role, usually implemented by an interface or abstract class. This role provides all the interfaces required for specific policy classes. ConcreteStrategy role: encapsulates related algorithms or behavioral advantages: You can use the policy mode to separate behavior from the environment. The environment class is responsible for maintaining and querying behavior classes, and various algorithms are provided in the specific strategy class (ConcreteStrategy. Because the algorithm and environment are independent, the increase, decrease, and modification of the algorithm will not affect the environment and the client. When a new promotion discount or an existing discount policy changes, you only need to implement a new strategy class and register it on the client. Policy mode is equivalent to "plug-in (Pluggable) algorithms". My personal understanding: Policy mode and factory mode place all objects to be instantiated into a class, then, the client directly uses the factory method to implement different operation strategies for different objects. The mode is to extract the methods in the factory, and then put the objects to be instantiated to the client to go To the instance. When I need to add different policies, I only need to add its instances on the client, and then upload the object as a parameter to the policy mode. The policy mode structure is shown as follows: Textbook instance: Mall discount code: [csharp] class cashcontext {// basic class Object private CashSuper cs; // when initializing (constructor), input the specific object public cashcontext (CashSuper csuper) {this. cs = csuper; // assign the csuper to cs, and then calculate the number of cash received by the cs object. // pass in different parameters, calculate the number of received cash in different ways} public double getresult (double money) // according to the specific policy object, call the method of its algorithm {return cs. acceptCash (money) ;}} the memo mode captures the internal state of an object without compromising encapsulation, and saves Status. in this way, the object can be restored to the previously saved state. the Memento mode is applicable to classes with complex functions, but which need to maintain or record the property history. or, if the attributes to be saved are only a small part of many attributes, originator can be restored to the previous state textbook instance based on the stored Memento information. The code for saving the game status is as follows: [csharp] // One initiating a human being: attacker, vitality, class GameRole {// alive private int vit; public int Vitality {get {return vit ;}set {vit = value ;}} // Attack force private int atk; public int Attack {get {return atk;} set {atk = value ;}// defense class private int def; publ Ic int Defense {get {return def;} set {def = value ;}}// the public void StateDisplay () {Console is displayed. writeLine ("current role status:"); Console. writeLine ("physical strength: {0}", this. vit); Console. writeLine ("Attack Strength: {0}", this. atk); Console. writeLine ("defense class: {0}", this. def); Console. writeLine ("");} // obtain the initial state public void GetInitState () {this. vit = 100; this. atk = 100; this. def = 100;} // combat public void Fight () {this. vit = 0; This. atk = 0; this. def = 0;} // Save the public RoleStateMemento SaveState () {// create a storage box return (new RoleStateMemento (vit, atk, def) when saving the role state ));} // restore the role state public void RecoveryState (RoleStateMemento memento) {this. vit = memento. vitality; this. atk = memento. attack; this. def = memento. defense; }}// a memorandum class: the content to be forgotten is stored in the memorandum // role status storage box class RoleStateMemento {private int vit; private int atk; private int d Ef; // The preceding attributes are public RoleStateMemento (int vit, int atk, int def) {this. vit = vit; this. atk = atk; this. def = def ;}// Vitality public int Vitality {get {return vit ;}set {vit = value ;}// Attack force public int Attack {get {return atk ;} set {atk = value ;}/// Defense Force public int Defense {get {return def ;}set {def = value ;}// the above are some functions of the storage box, it refers to the ability to read and write status such as vitality} // a manager class: encapsulate the memorandum class so that you only need to know the manager on the client. Class RoleStateCaretaker {private RoleStateMemento memento; public RoleStateMemento Memento {get {return memento;} set {memento = value ;}}} // client: // before the war, GameRole hejingyuan = new GameRole (); hejingyuan. getInitState (); hejingyuan. stateDisplay (); // Save the progress RoleStateCaretaker stateAdmin = new RoleStateCaretaker (); stateAdmin. memento = hejingyuan. saveState (); // serious loss during wartime hejingy Uan. fight (); hejingyuan. stateDisplay (); // hejingyuan. recoveryState (stateAdmin. memento); hejingyuan. stateDisplay (); Console. read (); personal understanding: Memorandum mode: When I want to save the memo, I will create a memorandum in the sponsor (game role) class, the memorandum class contains some content (attributes and methods) to be forgotten. The manager packs the Memorandum and assigns the sponsor memo to the Administrator on the client, in this way, the client does not need to know what I forgot. The iterator mode provides a way to access each element of an aggregate object sequentially without exposing the internal representation of the object. When you need to access a clustered object and traverse all these objects, you should consider applying them in the iterator mode: when you need to have multiple methods for aggregation, you can consider using the iterator mode. In general, the iterator mode separates the traversal behavior of the collection object, abstract An iterator class to take responsibility, so that the internal structure of the set is not exposed, and external code can access the data inside the set transparently. example of a textbook: the code for buying tickets by bus is as follows: [csharp] // Iterator abstract class Iterator {public abstract object First (); public abstract object Next (); public abstract object IsDone (); public abstract object CurrentItem ();} // The iterator class is a specific iterator class for traversing a clustered object // ConcreteIterator, inherited Iterator class ConcreteIterator: Iterator {// a specific aggregation object private ConcreteAggregate aggregate; private int current = 0; public ConcreteIterator (ConcreteAggregate aggregate) {this. aggregate = aggregate;} // pass the specific aggregation object into public override object First () {return aggregate [0];} public override object Next () during initialization () {object ret = null; current ++; if (current <aggregate. count) {ret = aggregate [current];} Return ret;} public override object IsDone () {return current> = aggregate. Count? True: false;} public override object CurrentItem () {return aggregate [current] ;}// a specific iterator is an operation on a specific clustered object, also rewrite the abstract Iterator // Aggregate abstract class Aggregate {public abstract Iterator CreateIterator ();} // The abstract aggregation class is to create an iterator // ConcreteAggregate. The specific aggregation class inherits Aggregate class ConcreteAggregate: Aggregate {private IList <object> items = new List <object> (); public override Iterator CreateIterator () {return new ConcreteIterator (this);} public int Count {get {return items. count ;}} public object this [int index] {get {return items [index];} set {items. insert (index, value) ;}}// the aggregate class contains the variables used to store the aggregate object, overwrites the abstract aggregation class, and aggregates the total number, and declares an index.

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.