首页 > 其他分享 >CSharp: Iterator Pattern

CSharp: Iterator Pattern

时间:2022-12-18 12:36:24浏览次数:33  
标签:iterator Iterator MusicFestival Pattern collection CSharp public

资源都来源于互联网

    /// <summary>
    /// 迭代器模式  Iterator Pattern
    /// </summary>
    public interface IIterableCollection
    {
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        IIterator CreateIterator();
    }

  /// <summary>
    /// 迭代器模式  Iterator Pattern
    /// </summary>
    public class FestivalCollection : IIterableCollection
    {

        /// <summary>
        /// 
        /// </summary>
        private readonly List<MusicFestival> _festivals = new();
        /// <summary>
        /// 
        /// </summary>
        public int Count => _festivals.Count;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="festival"></param>
        public void Add(MusicFestival festival) => _festivals.Add(festival);
        /// <summary>
        /// 
        /// </summary>
        /// <param name="index"></param>
        /// <returns></returns>
        public MusicFestival Get(int index) => _festivals[index];
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public IIterator CreateIterator() => new FestivalIterator(this);


    }

    /// <summary>
    ///  迭代器模式  Iterator Pattern
    /// </summary>
    public interface IIterator
    {
        /// <summary>
        /// 
        /// </summary>
        int Step { get; set; }
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        MusicFestival First();
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        MusicFestival Current();
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        bool MoveNext();
        /// <summary>
        /// 
        /// </summary>
        void Reset();

    }

 /// <summary>
    ///  迭代器模式  Iterator Pattern
    /// </summary>
    public class FestivalIterator : IIterator
    {

        /// <summary>
        /// /
        /// </summary>
        private readonly FestivalCollection _collection;
        /// <summary>
        /// 
        /// </summary>
        private int _position;
        /// <summary>
        /// /
        /// </summary>
        private int _step;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="collection"></param>
        public FestivalIterator(FestivalCollection collection)
        {
            _collection = collection;
            _position = -1;
            _step = 1;
        }

        // It's probably more logical to have a method for changing the step.
        // However, for demo purposes the idea was to show that iterator interface can contain properties too.
        /// <summary>
        /// 
        /// </summary>
        public int Step
        {
            get => _step;
            set
            {
                if (value <= 0)
                {
                    throw new ArgumentOutOfRangeException(nameof(value), "步长只能是正值。当前迭代器不支持倒退.");
                }

                _step = value;
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>

        public MusicFestival First()
        {
            _position = 0;
            return Current();
        }
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public MusicFestival Current() => _collection.Get(_position);
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public bool MoveNext()
        {
            var updatedPosition = _position + _step;

            if (updatedPosition < _collection.Count)
            {
                _position = updatedPosition;
                return true;
            }

            return false;
        }
        /// <summary>
        /// 
        /// </summary>
        public void Reset() => _position = -1;
    }

  /// <summary>
    /// 
    /// </summary>
    public class MusicFestival
    {

        /// <summary>
        ///  迭代器模式  Iterator Pattern
        /// </summary>
        /// <param name="name"></param>
        /// <param name="country"></param>
        public MusicFestival(string name, string country)
        {
            Name = name;
            Country = country;
        }
        /// <summary>
        /// 
        /// </summary>
        public string Name { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public string Country { get; set; }
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public override string ToString()
        {
            return $"姓名:{this.Name} 国家: {this.Country}";
        }
    }


  /// <summary>
    /// 迭代器模式  Iterator Pattern
    /// </summary>
    public static class MusicFestivalsExecutor
    {

        /// <summary>
        ///  迭代器模式  Iterator Pattern
        /// </summary>
        public static void Execute()
        {
            ConsoleExtension.WriteSeparator(" 迭代器模式  Iterator Pattern:Music festivals demo");

            var collection = new FestivalCollection();

            collection.Add(new MusicFestival("春", "中国"));
            collection.Add(new MusicFestival("四季之歌", "比利时"));
            collection.Add(new MusicFestival("春", "英国"));
            collection.Add(new MusicFestival("夏", "美国"));
            collection.Add(new MusicFestival("冬", "中国"));

            var iterator = collection.CreateIterator();

            Console.WriteLine("初始遍历.");
            Traverse(iterator);

            iterator.Reset();
            iterator.Step = 2;

            Console.WriteLine("\nT应跳过所有其他元素的第二个遍历.");
            Traverse(iterator);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="iterator"></param>
        private static void Traverse(IIterator iterator)
        {
            while (iterator.MoveNext())
            {
                var festival = iterator.Current();
                Console.WriteLine($"音乐节 {festival.Name} 发生在{festival.Country}.");
            }
        }
    }

  

调用:

 Geovin.Du.DuIterator.MusicFestivals.MusicFestivalsExecutor.Execute();

  

输出:

 迭代器模式  Iterator Pattern:Music festivals demo
--------------------------------------------------
初始遍历.
音乐节 春 发生在中国.
音乐节 四季之歌 发生在比利时.
音乐节 春 发生在英国.
音乐节 夏 发生在美国.
音乐节 冬 发生在中国.

T应跳过所有其他元素的第二个遍历.
音乐节 四季之歌 发生在比利时.
音乐节 夏 发生在美国.

  

标签:iterator,Iterator,MusicFestival,Pattern,collection,CSharp,public
From: https://www.cnblogs.com/geovindu/p/16990161.html

相关文章

  • Iterator接口
    1Iterator接口,是集合框架中的核心接口之一,用于遍历集合中元素。容器类,都有一个iterator方法用以返回一个实现了Iterator接口的对象(称作迭代器)2Iterator接口常用方法:......
  • 前端开发系列125-进阶篇之Iterator
    title:前端开发系列125-进阶篇之Iteratortags:categories:[]date:2019-08-0100:00:08本文简单说明[迭代器接口Iterator]()接口的基本使用,涉及Array、Set、M......
  • CSharp: Chain of Responsibility Pattern in donet core 6
     usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;namespaceGeovin.Du.DuChainOfResponsib......
  • C#实现观察者模式(Observer Pattern)的两种方式
    原文链接:https://www.jb51.net/article/260871.htm在观察者模式中有2个要素:一个是被观察对象,另一个是观察者。但被观察对象的状态发生改变会通知观察者。举例:把订阅报纸......
  • CSharp: Proxy Pattern in donet.core 6.0
     usingSystem;usingSystem.Collections.Generic;usingSystem.Data;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;namespaceGeovin.Du......
  • servlet的url-pattern匹配规则
     目录​​1url-pattern匹配规则说明​​​​2四种匹配规则优先顺序​​​​2.1 精确匹配​​​​2.2路径匹配​​​​2.3扩展名匹配​​​​2.4缺省匹配​​​​3需......
  • Cannot invoke “org.springframework.web.servlet.mvc.condition.PatternsRequestCon
    异常信息:Cannotinvoke“org.springframework.web.servlet.mvc.condition.PatternsRequestCondition.getPatterns()”because“this.condition”isnull出现该异常......
  • 服务网格 Pattern: Service Mesh
    服务网格是用于处理服务到服务通信的专用基础设施层。它负责通过包含现代云本机应用程序的复杂服务拓扑来可靠地传递请求。实际上,服务网格通常实现为轻量级网络代理的数组,这......
  • 《基于Csharp+OpenCV图像处理实战》 关于软件部署的7个步骤
    一是持续部署的方法;二是集中解决部署问题方法。操作系统最好使用主流系统,这样首先就解决了系列问题。我一般是建一个虚拟机来进行测试。1、首先是设置为Release模式2......
  • torchtext.vocab.build_vocab_from_iterator的参数介绍以及使用
    build_vocab_from_iterator的参数介绍以及使用因为使用的时候不知道specials参数是什么意思,网上也没找到一个比较好的解释,所以记录一下这个函数的作用是从一个可迭代对......