码迷,mamicode.com
首页 > 编程语言 > 详细

《精通Python设计模式》学习结构型之外观模式

时间:2018-08-04 21:37:03      阅读:121      评论:0      收藏:0      [点我收藏+]

标签:分享图片   format   div   设计模式   network   info   iss   隔离   elf   

这个我在工作中也有所应用的。

就是在真正的实现层上面,再封装一个函数的调用的。

这样就可以在内层函数作真正实现,

而外层调用函数对外开放,

隔离内外的变化性。

技术分享图片

 

from enum import Enum
from abc import ABCMeta, abstractmethod

State = Enum(State, new running sleeping restart zombie)

class User:
    pass

class Process:
    pass

class File:
    pass

class Server(metaclass=ABCMeta):
    @abstractmethod
    def __init__(self):
        pass

    def __str__(self):
        return self.name

    @abstractmethod
    def boot(self):
        pass

    @abstractmethod
    def kill(self, restart=True):
        pass

class FileServer(Server):
    def __init__(self):
        self.name = FileServer
        self.state = State.new

    def boot(self):
        print(booting the {}.format(self))
        self.state = State.running

    def kill(self, restart=True):
        print(Killing {}.format(self))
        self.state = State.restart if restart else State.zombie

    def create_file(self, user, name, permissions):
        print("trying to create the file ‘{}‘ for user ‘{}‘ with permissions ‘{}‘"
              .format(name, user, permissions))

class ProcessServer(Server):
    def __init__(self):
        self.name = ProcessServer
        self.state = State.new

    def boot(self):
        print(booting the {}.format(self))
        self.state = State.running

    def kill(self, restart=True):
        print(Killing {}.format(self))
        self.state = Stae.restart if restart else State.zobmie

    def create_process(self, user, name):
        print("trying to create process ‘{}‘ for user ‘{}‘"
              .format(name, user))

class WindowsServer:
    pass

class NetworkServer:
    pass


class OperatingSystem:
    def __init__(self):
        self.fs = FileServer()
        self.ps = ProcessServer()

    def start(self):
        [i.boot() for i in (self.fs, self.ps)]

    def create_file(self, user, name, permissions):
        return self.fs.create_file(user, name, permissions)

    def create_process(self, user, name):
        return self.ps.create_process(user, name)

def main():
    os = OperatingSystem()
    os.start()
    os.create_file(foo, hello, -rw-r-r)
    os.create_process(bar, ls /tmp)

if __name__ == __main__:
    main()

技术分享图片

《精通Python设计模式》学习结构型之外观模式

标签:分享图片   format   div   设计模式   network   info   iss   隔离   elf   

原文地址:https://www.cnblogs.com/aguncn/p/9419903.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!