Design Pattern - Adapter(C#)

来源:互联网 发布:淘宝运费险怎么开通 编辑:程序博客网 时间:2024/05/17 08:52

Definition

Convert the interface of a class into another interface clients expect. Adapter lets classes work together that couldn't otherwise because of incompatible interfaces.

Participants

    The classes and/or objects participating in this pattern are:

  • Target  (ChemicalCompound)
    • Defines the domain-specific interface that Client uses.
  • Adapter  (Compound)
    • Adapts the interface Adaptee to the Target interface.
  • Adaptee  (ChemicalDatabank)
    • Defines an existing interface that needs adapting.
  • Client  (AdapterApp)
    • Collaborates with objects conforming to the Target interface.

Sample Code in C#


This structural code demonstrates the Adapter pattern which maps the interface of one class onto another so that they can work together. These incompatible classes may come from different libraries or frameworks.

// --------------------------------------------------------------------------------------------------------------------// <copyright company="Chimomo's Company" file="Program.cs">// Respect the work.// </copyright>// <summary>// Structural Adapter Design Pattern.// </summary>// --------------------------------------------------------------------------------------------------------------------namespace CSharpLearning{    using System;    /// <summary>    /// Startup class for Structural Adapter Design Pattern.    /// </summary>    internal static class Program    {        #region Methods        /// <summary>        /// Entry point into console application.        /// </summary>        private static void Main()        {            // Create adapter and place a request            Target target = new Adapter();            target.Request();        }        #endregion    }    /// <summary>    /// The 'Target' class    /// </summary>    internal class Target    {        #region Public Methods and Operators        /// <summary>        /// The request.        /// </summary>        public virtual void Request()        {            Console.WriteLine("Called Target Request()");        }        #endregion    }    /// <summary>    /// The 'Adapter' class    /// </summary>    internal class Adapter : Target    {        #region Fields        /// <summary>        /// The adaptee.        /// </summary>        private Adaptee adaptee = new Adaptee();        #endregion        #region Public Methods and Operators        /// <summary>        /// The request.        /// </summary>        public override void Request()        {            // Possibly do some other work and then call SpecificRequest            this.adaptee.SpecificRequest();        }        #endregion    }    /// <summary>    /// The 'Adaptee' class    /// </summary>    internal class Adaptee    {        #region Public Methods and Operators        /// <summary>        /// The specific request.        /// </summary>        public void SpecificRequest()        {            Console.WriteLine("Called SpecificRequest()");        }        #endregion    }}// Output:/*Called SpecificRequest()*/


This real-world code demonstrates the use of a legacy chemical databank. Chemical compound objects access the databank through an Adapter interface.

// --------------------------------------------------------------------------------------------------------------------// <copyright company="Chimomo's Company" file="Program.cs">// Respect the work.// </copyright>// <summary>// Real-World Adapter Design Pattern.// </summary>// --------------------------------------------------------------------------------------------------------------------namespace CSharpLearning{    using System;    /// <summary>    /// Startup class for Real-World Adapter Design Pattern.    /// </summary>    internal static class Program    {        #region Methods        /// <summary>        /// Entry point into console application.        /// </summary>        private static void Main()        {            // Non-adapted chemical compound            var unknown = new Compound("Unknown");            unknown.Display();            // Adapted chemical compounds            Compound water = new RichCompound("Water");            water.Display();            Compound benzene = new RichCompound("Benzene");            benzene.Display();            Compound ethanol = new RichCompound("Ethanol");            ethanol.Display();        }        #endregion    }    /// <summary>    /// The 'Target' class    /// </summary>    internal class Compound    {        #region Fields        /// <summary>        /// The chemical.        /// </summary>        protected readonly string Chemical;        /// <summary>        /// The boiling point.        /// </summary>        protected float BoilingPoint;        /// <summary>        /// The melting point.        /// </summary>        protected float MeltingPoint;        /// <summary>        /// The molecular formula.        /// </summary>        protected string MolecularFormula;        /// <summary>        /// The molecular weight.        /// </summary>        protected double MolecularWeight;        #endregion        // Constructor        #region Constructors and Destructors        /// <summary>        /// Initializes a new instance of the <see cref="Compound"/> class.        /// </summary>        /// <param name="chemical">        /// The chemical.        /// </param>        public Compound(string chemical)        {            this.Chemical = chemical;        }        #endregion        #region Public Methods and Operators        /// <summary>        /// The display.        /// </summary>        public virtual void Display()        {            Console.WriteLine("\nCompound: {0} ------ ", this.Chemical);        }        #endregion    }    /// <summary>    /// The 'Adapter' class    /// </summary>    internal class RichCompound : Compound    {        #region Fields        /// <summary>        /// The bank.        /// </summary>        private ChemicalDatabank bank;        #endregion        // Constructor        #region Constructors and Destructors        /// <summary>        /// Initializes a new instance of the <see cref="RichCompound"/> class.        /// </summary>        /// <param name="name">        /// The name.        /// </param>        public RichCompound(string name)            : base(name)        {        }        #endregion        #region Public Methods and Operators        /// <summary>        /// The display.        /// </summary>        public override void Display()        {            // The Adaptee            this.bank = new ChemicalDatabank();            this.BoilingPoint = this.bank.GetCriticalPoint(this.Chemical, "B");            this.MeltingPoint = this.bank.GetCriticalPoint(this.Chemical, "M");            this.MolecularWeight = this.bank.GetMolecularWeight(this.Chemical);            this.MolecularFormula = this.bank.GetMolecularStructure(this.Chemical);            base.Display();            Console.WriteLine(" Formula: {0}", this.MolecularFormula);            Console.WriteLine(" Weight : {0}", this.MolecularWeight);            Console.WriteLine(" Melting Pt: {0}", this.MeltingPoint);            Console.WriteLine(" Boiling Pt: {0}", this.BoilingPoint);        }        #endregion    }    /// <summary>    /// The 'Adaptee' class    /// </summary>    internal class ChemicalDatabank    {        // The databank 'legacy API'        #region Public Methods and Operators        /// <summary>        /// The get critical point.        /// </summary>        /// <param name="compound">        /// The compound.        /// </param>        /// <param name="point">        /// The point.        /// </param>        /// <returns>        /// The <see cref="float"/>.        /// </returns>        public float GetCriticalPoint(string compound, string point)        {            // Melting Point            if (point == "M")            {                switch (compound.ToLower())                {                    case "water":                        return 0.0f;                    case "benzene":                        return 5.5f;                    case "ethanol":                        return -114.1f;                    default:                        return 0f;                }            }            switch (compound.ToLower())            {                case "water":                    return 100.0f;                case "benzene":                    return 80.1f;                case "ethanol":                    return 78.3f;                default:                    return 0f;            }        }        /// <summary>        /// The get molecular structure.        /// </summary>        /// <param name="compound">        /// The compound.        /// </param>        /// <returns>        /// The <see cref="string"/>.        /// </returns>        public string GetMolecularStructure(string compound)        {            switch (compound.ToLower())            {                case "water":                    return "H20";                case "benzene":                    return "C6H6";                case "ethanol":                    return "C2H5OH";                default:                    return string.Empty;            }        }        /// <summary>        /// The get molecular weight.        /// </summary>        /// <param name="compound">        /// The compound.        /// </param>        /// <returns>        /// The <see cref="double"/>.        /// </returns>        public double GetMolecularWeight(string compound)        {            switch (compound.ToLower())            {                case "water":                    return 18.015;                case "benzene":                    return 78.1134;                case "ethanol":                    return 46.0688;                default:                    return 0d;            }        }        #endregion    }}// Output:/*Compound: Unknown ------Compound: Water ------ Formula: H20 Weight : 18.015 Melting Pt: 0 Boiling Pt: 100Compound: Benzene ------ Formula: C6H6 Weight : 78.1134 Melting Pt: 5.5 Boiling Pt: 80.1Compound: Ethanol ------ Formula: C2H5OH Weight : 46.0688 Melting Pt: -114.1 Boiling Pt: 78.3*/

原创粉丝点击