python設計模式之介面卡模式

為不為發表於2019-01-03
class Page:
    def __init__(self,pageNum):
        self.__pageNum=pageNum
    def getContent(self):
        print("this is page "+str(self.__pageNum)+"'s content" )
# t=Page(5)
# t.getContent()
class Catalogue:
    def __init__(self,title):
        self.__title=title
        self.__catalogues=[]
        self.addCatalogue("one")
        self.addCatalogue("two")
    def addCatalogue(self,catalogue):
        self.__catalogues.append(catalogue)
    def showCatalogues(self):
        print("the title is "+self.__title)
        for o in self.__catalogues:
            print(o)
# t=Catalogue("失控");
# t.showCatalogues();
class IBook:
    def parseFile(self,filePath):
        pass
    def getCatalogue(self):
        pass
    def getPage(self,pageNum):
        pass
    def getTotalPageCount(self):
        pass
class TxtBook(IBook):
    def parseFile(self,filePath):
        print(filePath+"parse success")
        self.__pageTotalCount=500
        return True
    def getCatalogue(self):
        return Catalogue("TXT電子書")
    def getTotalPageCount(self):
        return self.__pageTotalCount
    def getPage(self,pageNum):
        return Page(pageNum)

import  os
class Reader:
    def __init__(self,name):
        self.__name=name;
        self.__filePath=""
        self.__curBook=None
        self.__curPageNum=-1
    def __initBook(self,filePath):
        self.__filePath=filePath
        extName=os.path.splitext(filePath)[1]
        if(extName.lower()==".txt"):
            self.__curBook=TxtBook()
    def openFile(self,filePath):
        self.__initBook(filePath)
        if(self.__curBook is not None):
            result=self.__curBook.parseFile(filePath)
            if(result):
                self.__curPageNum=1
            return result
        return False
    def showCatalogue(self):
        self.__curBook.getCatalogue().showCatalogues()
# t=Reader("xx閱讀器")
# t.openFile("xx.txt")
# t.showCatalogue()

原始碼有一個閱讀器,他可以開啟txt檔案,現要求其支援第三方pdf型別,這時就可以用介面卡模式了

相關文章