"C # design mode-Visitor mode"

Source: Internet
Author: User

I. Definition of the visitor pattern:

Represents an operation that acts on each element in an object structure. It allows you to define new actions that act on these elements without changing the individual element classes.

Two. Structure and role of the visitor pattern:


1.Visitor Abstract visitor role, which declares an access operation interface for the specific element role in the object structure. The name and parameters of the operation interface identify the specific element role that sends the access request to the specific visitor, so that the visitor can access it directly through the specific interface of the element role.
2.ConcreteVisitor. The specific visitor role that implements the interface for the visitor declaration.
3.Element defines an accepted access operation (accept ()), which takes a visitor (Visitor) as a parameter.
A 4.ConcreteElement concrete element that implements the accepted interface defined by the abstract element.
The 5.ObjectStructure structure object role, which is an essential role for using the visitor pattern. It has the following characteristics: An element that can enumerate it, a high-level interface to allow visitors to access its elements, or, if necessary, a composite object or a aggregation (such as a list or unordered collection).

Three. Implementation of the visitor pattern:

In life, we have to go to the hospital, when we registered to find the attending doctor's doctor after the illness, will give you open a prescription, this time you need to pay, by pricing doctor charge, then you take the pay list and then go to find the pharmacist prescription. Traditionally, we may have written a pricing class, which is based on the name of the drug to determine how much to charge; write a grasping pharmacist according to prescription above the name to determine where to go prescription. It is possible to use switch to determine, so that the drug will change the code of pricing personnel and pharmacy workers.

The purpose of the visitor pattern is to encapsulate some operations that are applied to a data structure element, and once those operations need to be modified, the data structure that accepts the operation can remain intact. Provides a variety of access operations for different types of elements, and can add new modes of operation without modifying the original system, which is the pattern motive of the visitor pattern.

//<  Summary>///abstract visitor///</summary> public abstract class Visitor {protected string name {get; Set        } public Visitor (string name) {this.name = name;        } public abstract void visitor (Medicinea a);    public abstract void Visitor (Medicineb b); }
//< Summary>///Specific visitors: pricing//</summary> public class Charger:visitor {public Charger (string na Me): Base (name) {} public override void Visitor (Medicinea a) {Console.WriteLine ("Pricing:" +this.na        me+ "Administration" +a.getname () + "Price:" +a.getprice ()); } public override void visitor (Medicineb b) {Console.WriteLine ("Pricing:" + THIS.name + "dosing" + b.get        Name () + "Price:" + b.getprice ()); }    }
//< Summary>///Specific visitors: Pharmacy worker///</summary> public class Workerofpharmacy:visitor {public Workero Fpharmacy (string name): base (name) {} public override void Visitor (Medicinea a) {Console.Write        Line ("Pharmacy worker" +this.name+ ", Take Medicine:" +a.getname ()); } public override void visitor (Medicineb b) {Console.WriteLine ("Pharmacy worker" + THIS.name + ", take medicine:" + b.ge        Tname ()); }    }
//< Summary>///Abstract elements: Medicine//</summary> public abstract class Medicine {protected string name {GE T Set        } protected double price {get; set;}            Public Medicine (string name, double price) {this.name = name;        This.price = Price;        } public string GetName () {return name;        } public double GetPrice () {return price;        public void Setprice (double price) {this.price = Price;    } public abstract void Accept (Visitor Visitor); }
    <summary>    ///specific elements: a name medicine///    </summary> public  class Medicinea:medicine    {        Public Medicinea (string name, double price): base (name, price) {} public        override void Accept (Visitor Visitor)        {            Visitor.visitor (this);        }    }
    <summary>    ///specific elements: B name Medicine///    </summary> public    class Medicineb:medicine    {        Public Medicineb (string name, double price): base (name, price) {} public        override void Accept (Visitor Visitor) 
   
    {            Visitor.visitor (this);        }    }
   
//< Summary>///specific elements: prescription//</summary> public class Presciption {private list<medicine> li        Stmedicine = new list<medicine> (); public void Accpet (Visitor Visitor) {foreach (var item in listmedicine) {ite            M.accept (visitor); }} public void Add (Medicine med) {listmedicine.        Add (MED); } public void Remove (Medicine med) {listmedicine.        Remove (MED); }    }
    <summary>//    C # design mode-visitor mode/    //</summary> class program    {        static void Main ( String[] args)        {            //drug type            Medicine a = new Medicinea ("Medicine A", "ten");            Medicineb B = new Medicineb ("Drug B", +);            Prescription            presciption presciption = new presciption ();            Presciption.add (a);            Presciption.add (b);            Visitor charger = new Charger ("Zhang San");    Pricing            Visitor workerofpharmacy = new Workerofpharmacy ("John Doe");//Prescription Presciption.accpet            (charger);//Pricing            Console.WriteLine ();            Presciption.accpet (workerofpharmacy); Prescription        }    }



Four. Visitor pattern pros and Cons:

Advantages:
1, making new access operations easier.
2, can enable the user without modifying the existing class hierarchy, define the operation of the class hierarchy.
3. The access behavior of the element objects is concentrated in a visitor object instead of being scattered among the element classes.
Disadvantages:
1. It is difficult to add new element classes. In visitor mode, each addition of a new element class means adding a new abstraction to the abstract visitor role and adding specific actions to each specific visitor class, violating the requirement of the "open and close principle".
2, destroy the package. When the visitor pattern is used, the encapsulation of the combo class is broken.
3, more difficult to understand

Five. Usage scenarios:

1. The classes of objects in the object structure seldom change, but it is often necessary to define new operations on this object structure.
2. There are many different and unrelated operations that need to be made on objects in an object structure, and you need to avoid classes that let these operations "contaminate" those objects, and you do not want to modify them when adding new operations.

"C # design mode-Visitor mode"

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.