程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python design pattern - behavioral pattern - state pattern

編輯:Python

Catalog

List of articles

  • Catalog
  • The state pattern
  • Application scenarios
  • Code example

The state pattern

The state pattern , When the internal state of an object changes , Allow objects to perform different processes .

advantage

  • Encapsulates the state transition rules .
  • Enumerates possible states , Before enumerating States, you need to determine the kind of state .
  • Put all the behaviors related to a state into a class , And it's easy to add new states , Just changing the state of the object can change the behavior of the object .
  • Allows state transformation logic to be integrated with state objects , Instead of a huge conditional block .
  • You can have multiple environment objects share a state object , So as to reduce the number of objects in the system .

shortcoming

  • The use of state patterns will inevitably increase the number of system classes and objects .
  • The structure and implementation of state patterns are complex , Improper use will lead to confusion of program structure and code .
  • State mode pair “ Opening and closing principle ” Not so good , For a state mode that can switch states , Adding a new state class requires modifying the source code responsible for state transformation , Otherwise, you cannot switch to the new state , In addition, to modify the behavior of a state class, you need to modify the source code of the corresponding class .

Application scenarios

  • A scene in which behavior changes as states change .
  • Conditions 、 Substitute of branch statement .

Code example

This is a state diagram , have “ Yes 25 Cents ”、“ No, 25 Cents ”、“ Sell candy ”、“ Candy sold out ” this 4 Status . It also corresponds to 4 An action :“ input 25 Cents ”,“ return 25 Cents ”,“ Turn the crank ” and “ Give out candy ”.

class State:
# Definition state Base class 
def insert_quarter(self):
pass
def eject_quarter(self):
pass
def turn_crank(self):
pass
def dispense(self):
pass
class SoldOutState(State):
# Inherit State class 
def __init__(self, gumball_machine):
self.gumball_machine = gumball_machine
def __str__(self):
return "sold_out"
def insert_quarter(self):
print("You can't insert a quarter, the machine is sold out")
def eject_quarter(self):
print("You can't eject, you haven't inserted a quarter yet")
def turn_crank(self):
print("You turned, but ther are no gumballs")
def dispense(self):
print("No gumball dispensed")
class SoldState(State):
# Inherit State class 
def __init__(self, gumball_machine):
self.gumball_machine = gumball_machine
def __str__(self):
return "sold"
def insert_quarter(self):
print("Please wait, we're already giving you a gumball")
def eject_quarter(self):
print("Sorry, you already turned the crank")
def turn_crank(self):
print("Turning twice doesn't get you another gumball")
def dispense(self):
self.gumball_machine.release_ball()
if gumball_machine.count > 0:
self.gumball_machine.state = self.gumball_machine.no_quarter_state
else:
print("Oops, out of gumballs!")
self.gumball_machine.state = self.gumball_machine.soldout_state
class NoQuarterState(State):
# Inherit State class 
def __init__(self, gumball_machine):
self.gumball_machine = gumball_machine
def __str__(self):
return "no_quarter"
def insert_quarter(self):
# Coin-operated And change the State 
print("You inserted a quarter")
self.gumball_machine.state = self.gumball_machine.has_quarter_state
def eject_quarter(self):
print("You haven't insert a quarter")
def turn_crank(self):
print("You turned, but there's no quarter")
def dispense(self):
print("You need to pay first")
class HasQuarterState(State):
# Inherit State class 
def __init__(self, gumball_machine):
self.gumball_machine = gumball_machine
def __str__(self):
return "has_quarter"
def insert_quarter(self):
print("You can't insert another quarter")
def eject_quarter(self):
print("Quarter returned")
self.gumball_machine.state = self.gumball_machine.no_quarter_state
def turn_crank(self):
print("You turned...")
self.gumball_machine.state = self.gumball_machine.sold_state
def dispense(self):
print("No gumball dispensed")
class GumballMachine:
def __init__(self, count=0):
self.count = count
# Find all the States , And create instance variables to hold the current state , Then define the value of the State 
self.soldout_state = SoldOutState(self)
self.no_quarter_state = NoQuarterState(self)
self.has_quarter_state = HasQuarterState(self)
self.sold_state = SoldState(self)
if count > 0:
self.state = self.no_quarter_state
else:
self.state = self.soldout_state
def __str__(self):
return ">>> Gumball machine current state: %s" % self.state
def insert_quarter(self):
# input 25 Cents 
self.state.insert_quarter()
def eject_quarter(self):
# return 25 branch 
self.state.eject_quarter()
# print("state", self.state, type(self.state))
def turn_crank(self):
# Turn the crank 
# print("state", self.state, type(self.state))
self.state.turn_crank()
def release_ball(self):
# Give out candy 
print("A gumball comes rolling out the slot...")
if self.count > 0:
self.count -= 1
if __name__ == "__main__":
# Here's the code test 
gumball_machine = GumballMachine(5) # Load 5 A candy 
print(gumball_machine)
gumball_machine.insert_quarter() # input 25 Cents 
gumball_machine.turn_crank() # Turn the crank 
print(gumball_machine)
gumball_machine.insert_quarter() # input 25 Cents 
gumball_machine.eject_quarter() # Refund 
gumball_machine.turn_crank() # Turn the crank 
print(gumball_machine)
gumball_machine.insert_quarter() # input 25 Cents 
gumball_machine.turn_crank() # Turn the crank 
gumball_machine.insert_quarter() # input 25 Cents 
gumball_machine.turn_crank() # Turn the crank 
gumball_machine.eject_quarter() # Refund 
print(gumball_machine)

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved