Decorator 在程序运行时生成新的操作,这些新的操作是原有的操作的变体

it2022-05-09  27

ISimpleWriter  1using System; 2using System.Collections.Generic; 3using System.Text; 4 5namespace Gof.Nan.Test.Decorator 6{ 7    public interface ISimpleWriter 8    { 9        void Write(char c);10        void Write(string s);11        void WriteLine();12        void Close();13    }14} SimpleStreamWriter  1using System; 2using System.Collections.Generic; 3using System.Text; 4using System.IO; 5 6namespace Gof.Nan.Test.Decorator 7{ 8    public class SimpleStreamWriter : StreamWriter,ISimpleWriter 9    {10        public SimpleStreamWriter(Stream s)11            : base(s)12        13        }1415        public SimpleStreamWriter(string path)16            : base(path)17        {18        }19    }20} OozinozFilter  1using System; 2using System.Collections.Generic; 3using System.Text; 4 5namespace Gof.Nan.Test.Decorator 6{ 7    public abstract class OozinozFilter : ISimpleWriter 8    { 9        protected ISimpleWriter _writer;1011        public OozinozFilter(ISimpleWriter w)12        {13            _writer = w;14        }1516        ISimpleWriter 成员#region ISimpleWriter 成员1718        public abstract void Write(char c);1920        public virtual void Write(string s)21        {22            foreach (char c in s.ToCharArray())23            {24                Write(c);25            }26        }2728        public virtual void WriteLine()29        {30            _writer.WriteLine();31        }3233        public void Close()34        {35            _writer.Close();36        }3738        #endregion39    }40} LowerCaseFilter  1using System; 2using System.Collections.Generic; 3using System.Text; 4 5namespace Gof.Nan.Test.Decorator 6{ 7    public class LowerCaseFilter : OozinozFilter 8    { 9        public LowerCaseFilter(ISimpleWriter w)10            : base(w)11        {12        }1314        public override void Write(char c)15        {16            _writer.Write(char.ToLower(c));17        }18    }19}20 客户代码  1using System; 2using System.Collections.Generic; 3using System.Text; 4 5namespace Gof.Nan.Test.Decorator 6{ 7    public class ShowLowerCase 8    { 9        static void Main(string[] args)10        {11            ISimpleWriter w = new SimpleStreamWriter("sample.txt");12            ISimpleWriter x = new LowerCaseFilter(w);13            x.Write("This Text,notably ALL in LoweR CasE!");14            x.Close();15        }16    }17} 类图:   The Decorator Pattern attaches additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality.

转载于:https://www.cnblogs.com/nanshouyong326/archive/2007/01/15/620897.html

相关资源:DirectX修复工具V4.0增强版

最新回复(0)