zoukankan      html  css  js  c++  java
  • 设计模式之迭代模式

    class BaseIterator:
        """迭代器"""
        def __init__(self, data):
            self.__data = data
            self.toBegin()
    
        def toBegin(self):
            """将指针移至起始位置"""
            self.__curIdx = -1
    
        def toEnd(self):
            """将指针移至结尾位置"""
            self.__curIdx = len(self.__data)
    
        def next(self):
            """移动至下一个元素"""
            if(self.__curIdx < len(self.__data) - 1):
                self.__curIdx += 1
                return True
            else:
                self.__curIdx += 1
                return False
    
        def prevoius(self):
            """移动至上一个元素"""
            if(self.__curIdx > 0):
                self.__curIdx -= 1
                return True
            else:
                self.__curIdx -= 1
                return False
    
        def current(self):
            """获取当前的元素"""
            return self.__data[self.__curIdx] if (self.__curIdx < len(self.__data)) and self.__curIdx >= 0 else None
    
    
    
    class NumberSequence:
        """生成一个间隔为step的数字系列"""
        def __init(self, init, step, max=100):
            self.__data = init
            self.__step = step
            self.__max = max
    
        def __iter__(self):
            return self
    
        def __next__(self):
            if(self.__data < self.__data + self.__step):
                temp = self.__data
                self.__data += self.__step
                return temp
            else:
                raise StopIteration
    
    
    if __name__ == "__main__":
        print("从前往后遍历:")
        iterator = BaseIterator(range(10))
        while(iterator.next()):
            customer = iterator.current()
            print(customer, end="	")
        print()
        print("从后往前遍历:")
        while(iterator.prevoius()):
            customer = iterator.current()
            print(customer, end="	")
  • 相关阅读:

    使用docker构建fastdfs
    docker测试
    java测试远程调试(转载)
    mac上运行mongodb-community
    mac上zookeeper服务开启,kafka开启
    idea注册配置
    java-集合
    selenium+phantomjs爬取bilibili
    [转载] Python数据类型知识点全解
  • 原文地址:https://www.cnblogs.com/loveprogramme/p/13034660.html
Copyright © 2011-2022 走看看