[Python design mode] 16th Chapter work, work, work, overtime-state mode

Source: Internet
Author: User

GitHub Address: Https://github.com/cheesezh/python_design_patterns

Topic

Use code to simulate the work of the day, Good morning state, noon want to sleep, the afternoon gradually recover, overtime bitter torment.

Basic version-Function edition
hour = 0work_finished = Falsedef write_program():    if hour < 12:        print("当前时间: {} 点, 上午工作,精神百倍".format(hour))    elif hour < 13:        print("当前时间: {} 点, 饿了,午饭,犯困,午休".format(hour))    elif hour < 17:        print("当前时间: {} 点, 下午状态还可以,继续努力".format(hour))    elif work_finished == True:        print("当前时间: {} 点, 收工,下班".format(hour))    elif hour < 21:        print("当前时间: {} 点, 加班中,好累".format(hour))    else:        print("当前时间: {} 点, 不行了,睡着了".format(hour))        hour = 9write_program()hour = 10write_program()hour = 12write_program()hour = 13write_program()hour = 14write_program()hour = 17work_finished = True# work_finished = Falsewrite_program()hour = 19write_program()hour = 22write_program()
当前时间: 9 点, 上午工作,精神百倍当前时间: 10 点, 上午工作,精神百倍当前时间: 12 点, 饿了,午饭,犯困,午休当前时间: 13 点, 下午状态还可以,继续努力当前时间: 14 点, 下午状态还可以,继续努力当前时间: 17 点, 收工,下班当前时间: 19 点, 收工,下班当前时间: 22 点, 收工,下班
Improved version 1.0--preliminary package
Class work (): Def __init__ (self): self.hour = 0 self.task_finished = False def write_program (s ELF): If Self.hour < 12:print ("current time: {} points, morning work, Spirit hundredfold". Format (self.hour)) Elif Self.hour < 13:print ("Current time: {} point, hungry, lunch, sleepy, lunch Break". Format (self.hour)) Elif Self.hour < 17:print ("current time: { } points, the afternoon state can also, continue to work ". Format (self.hour)) elif self.work_finished = = True:print (" Current time: {} point, end of day, off duty ". Format (            Self.hour) Elif Self.hour < 21:print ("current time: {} point, overtime, good tired". Format (Self.hour)) Else: Print ("Current time: {} dot, no, asleep". Format (self.hour)) work = Work () Work.hour = 9work.write_program () Work.hour = 10wo Rk.write_program () Work.hour = 12work.write_program () Work.hour = 13work.write_program () Work.hour = 14work.write_ Program () Work.hour = 17work.work_finished = true# work_finished = Falsework.write_program () Work.hour = 19work.write_ Program () Work.hour = 22work.write_program() 
当前时间: 9 点, 上午工作,精神百倍当前时间: 10 点, 上午工作,精神百倍当前时间: 12 点, 饿了,午饭,犯困,午休当前时间: 13 点, 下午状态还可以,继续努力当前时间: 14 点, 下午状态还可以,继续努力当前时间: 17 点, 收工,下班当前时间: 19 点, 收工,下班当前时间: 22 点, 收工,下班
Comments
    • The Write_program method in this class is too long, and there are many branches of judgment, which means it is too much of a responsibility. Object-oriented design is actually to achieve the responsibility of code decomposition. So this class goes against it 单一职责原则 ;
    • In addition, there are so many judgments in the Write_program method that any changes or additions to the requirements need to be changed. So this class also violates 开放-封闭原则 ;
State mode

State mode, when an object's internal state change is allowed to change its behavior, the object looks like it has changed its class. [DP]

State mode mainly solves the situation when the conditional expression that controls an object state transition is too complex. It is possible to simplify the complex judgment logic by transferring the judgment logic of the state to a series of classes representing different states.

from abc import ABCMeta, abstractmethodclass State():    __metaclass__ = ABCMeta        @abstractmethod    def handle(self, context):        pass        class StateA(State):        def handle(self, context):        context.set_state(StateB())        class StateB(State):        def handle(self, context):        context.set_state(StateA())        class Context():        def __init__(self, state):        self.state = state            def set_state(self, state):        self.state = state        print("当前状态: {}".format(self.state.__class__))            def request(self):        self.state.handle(self)  # 精髓                def main():    context = Context(StateA())    context.request()    context.request()    context.request()    context.request()    main()  
当前状态: <class '__main__.StateB'>当前状态: <class '__main__.StateA'>当前状态: <class '__main__.StateB'>当前状态: <class '__main__.StateA'>
The benefits and usefulness of State mode

The benefit of the state pattern is that the behavior associated with a particular state is localized and the behavior of the different states is separated. [DP] is to put a particular state-related behavior into an object, because all the state-related code exists in a concretstate, so by defining a new subclass can easily add new states and Transformations [DP]. The purpose of this is to eliminate the large conditional branching statements, which make it difficult to modify and extend the large branch judgments. The state mode reduces the dependency between the States by transferring the various state transitions to the sub-classes of the status.

When do you need to consider using state mode? A state pattern can be used when an object's behavior depends on its state, and it must change its behavior according to state at run time. In addition, if the business requires that a business has multiple states, usually some enumeration constants, the change of state depends on a large number of branch judgment statements, you should consider defining each of the business States as a state subclass so that the objects can change independently of other objects. It is not difficult to increase or decrease the state of the business or change the status process if the customer needs change one day.

Improved version 2.0--state mode
From ABC import Abcmeta, Abstractmethodclass State (): __metaclass__ = Abcmeta @abstractmethod def write_progr AM (self, work): Pass class Forenoonstate (state): Def write_program (self, work): if Work.hour <            12:print ("Current time: {} point, morning work, Spirit hundredfold". Format (Work.hour)) Else:work.set_state (Noonstate ())  Work.write_program () class Noonstate: Def write_program (self, work): if Work.hour < 13:print ("current time: {} point, hungry, lunch, sleepy, lunch Break". Format (Work.hour)) Else:work.set_state (afternoonst Ate ()) Work.write_program () class Afternoonstate (state): Def write_program (self,            Work): If Work.hour < 17:print ("current time: {} Point, PM State can also continue efforts". Format (Work.hour)) Else: Work.set_state (Eveningstate ()) Work.write_program () class Eveningstate (state): Def Write_pro       Gram (self, work): if work.task_finished = = True:work.set_state (Reststate ()) Work.write_program () elif Work.ho ur < 21:print ("current time: {} points, overtime, very tired". Format (Work.hour)) Else:work.set_state (Sleepingstate ( )) Work.write_program () class Sleepingstate (state): Def write_program (self, work): PRI        NT ("Current time: {} dot, no, asleep". Format (work.hour)) class Reststate (state): Def write_program (self, work): Print ("Current time: {} point, end of day, off duty". Format (Work.hour)) class work (): Def __init__ (self, State): s Elf.state = state Self.hour = 0 self.task_finished = False def set_state (self, State): SEL F.state = State Def-Write_program (self): Self.state.write_program (self) # essence work = Work (Forenoo Nstate ()) Work.hour = 9work.write_program () Work.hour = 10work.write_program () Work.hour = 12work.write_program () Work.hour = 13work.write_program () woRk.hour = 14work.write_program () work.hour = 17work.work_finished = true# work_finished = Falsework.write_program ()             Work.hour = 19work.write_program () Work.hour = 22work.write_program ()
当前时间: 9 点, 上午工作,精神百倍当前时间: 10 点, 上午工作,精神百倍当前时间: 12 点, 饿了,午饭,犯困,午休当前时间: 13 点, 下午状态还可以,继续努力当前时间: 14 点, 下午状态还可以,继续努力当前时间: 17 点, 加班中,好累当前时间: 19 点, 加班中,好累当前时间: 22 点, 不行了,睡着了
Comments

If the boss stipulates that "employees must leave the company before 20 o'clock", then it is only necessary to add a "forced off" condition and then change the "evening work". And this is the code that does not affect other states.

[Python design mode] 16th Chapter work, work, work, overtime-state mode

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.