Created
March 13, 2020 14:41
-
-
Save Ah-da-Coder/bb7115c885f2e1fc950bb3d18a54149d to your computer and use it in GitHub Desktop.
StateパターンのPythonコード
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class State(): | |
| """Stateパターンの抽象クラス | |
| """ | |
| def action(self): | |
| """動作メソッド | |
| Returns: | |
| None | |
| """ | |
| raise NotImplementedError("action()は抽象メソッドでござる") | |
| def greeting(self): | |
| """挨拶メソッド | |
| Returns: | |
| None | |
| """ | |
| raise NotImplementedError("greeting()は抽象メソッドでござる") | |
| class TheBeginningOfTheDay(State): | |
| """Stateパターンの具象クラス。(朝クラス) | |
| """ | |
| def __init__(self): | |
| """コンストラクタ | |
| """ | |
| self.action_name = "起きる" | |
| self.greeting_word = "おはよう" | |
| def action(self): | |
| """動作メソッド | |
| Returns: | |
| None | |
| """ | |
| print(self.action_name) | |
| def greeting(self): | |
| """挨拶メソッド | |
| Returns: | |
| None | |
| """ | |
| print(self.greeting_word) | |
| class TheEndOfTheDay(State): | |
| """Stateパターンの具象クラス。(夜クラス) | |
| """ | |
| def __init__(self): | |
| """コンストラクタ | |
| """ | |
| self.action_name = "寝る" | |
| self.greeting_word = "おやすみ" | |
| def action(self): | |
| """動作メソッド | |
| Returns: | |
| None | |
| """ | |
| print(self.action_name) | |
| def greeting(self): | |
| """挨拶メソッド | |
| Returns: | |
| None | |
| """ | |
| print(self.greeting_word) | |
| class Context: | |
| """StateパターンのContextクラス | |
| """ | |
| def __init__(self): | |
| """コンストラクタ | |
| """ | |
| self.the_beginning_of_the_day = TheBeginningOfTheDay() | |
| self.the_end_of_the_day = TheEndOfTheDay() | |
| self.state = self.the_beginning_of_the_day | |
| def change_state(self, scene): | |
| """State変更メソッド | |
| Args: | |
| scene (str): 昼または夜 | |
| Returns: | |
| None | |
| """ | |
| if scene == "一日の始まり": | |
| self.state = self.the_beginning_of_the_day | |
| elif scene == "一日の終わり": | |
| self.state = self.the_end_of_the_day | |
| else: | |
| raise ValueError() | |
| def action(self): | |
| """動作メソッド | |
| Returns: | |
| None | |
| """ | |
| self.state.action() | |
| def greeting(self): | |
| """挨拶メソッド | |
| Return: | |
| None | |
| """ | |
| self.state.greeting() | |
| def main(): | |
| print("<<一日の始まり>>") | |
| context = Context() | |
| context.action() | |
| context.greeting() | |
| print("===") | |
| print("<<一日の終わり>>") | |
| context.change_state("一日の終わり") | |
| context.greeting() | |
| context.action() | |
| if __name__ == "__main__": | |
| main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment