Python デザインパターン サンプルコード Factory Method
Mark Summerfield『実践 Python 3』デザインパターンのサンプルコード
Python3(3.11)で動くソースコード(.pyファイル .ipynbファイル)あります
「anaconda3」on .py「PyCharm」.ipynb「Jupyter Notebook」
(2023-11-16)Python3.11で動作確認済み
【重要な注意】本プログラムは,.docファイルを出力します。その使い方は不明です。
「PyCharm」上に「Jupyter Notebook」上に出力されるのは出力ファイルのディレクトリだけです。そのディレクトリは「os.path」で指定しています。
wrote 'C:\Users\yamak\AppData\Local\Temp\gameboard1.doc'
wrote 'C:\Users\yamak\AppData\Local\Temp\gameboard2.doc'
wrote 'C:\Users\yamak\AppData\Local\Temp\gameboard3.doc'
wrote 'C:\Users\yamak\AppData\Local\Temp\gameboard4.doc
「AppData」は隠しフォルダであり,
エクスプローラ(ユーザーアカウント)→表示→表示→隠しファイル
により,エクスプローラに他のフォルダのように表示されます。
上のディレクりのフォルダの中にはたくさんのファイルが有りますが,更新日時でソートすれば1番目に見つかります。
AbstractBoard Piece (populate_board, __str__) () ↑ ↑ ↑ CheckerBoard ChessBoard BalckDraught,etc (populate_board) (populate_board) (__new__)
class BlackDraught(Piece): __slots__ = () def __new__(Class): return super().__new__(Class, "\N{black draughts man}")
class AbstractBoard: def populate_board(self): raise NotImplementedError()
def main(): checkers = CheckersBoard() print(checkers) chess = ChessBoard() print(chess)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226
#!/usr/bin/env python3 # Copyright c 2012-13 Qtrac Ltd. All rights reserved. # This program or module is free software: you can redistribute it # and/or modify it under the terms of the GNU General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. It is provided for # educational purposes and is distributed in the hope that it will be # useful, but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. import io import os import sys import tempfile BLACK, WHITE = ("BLACK", "WHITE") def main(): checkers = CheckersBoard() print(checkers) chess = ChessBoard() print(chess) if sys.platform.startswith("win"): filename = os.path.join(tempfile.gettempdir(), "gameboard1.doc") with open(filename, "w", encoding="utf-8") as file: file.write(sys.stdout.getvalue()) print("wrote '{}'".format(filename), file=sys.__stdout__) if sys.platform.startswith("win"): def console(char, background): return char or " " sys.stdout = io.StringIO() else: def console(char, background): return "\x1B[{}m{}\x1B[0m".format( 43 if background == BLACK else 47, char or " ") class AbstractBoard: def __init__(self, rows, columns): self.board = [[None for _ in range(columns)] for _ in range(rows)] self.populate_board() def populate_board(self): raise NotImplementedError() def __str__(self): squares = [] for y, row in enumerate(self.board): for x, piece in enumerate(row): square = console(piece, BLACK if (y + x) % 2 else WHITE) squares.append(square) squares.append("\n") return "".join(squares) class CheckersBoard(AbstractBoard): def __init__(self): super().__init__(10, 10) def populate_board(self): for x in range(0, 9, 2): for row in range(4): column = x + ((row + 1) % 2) self.board[row][column] = BlackDraught() self.board[row + 6][column] = WhiteDraught() class ChessBoard(AbstractBoard): def __init__(self): super().__init__(8, 8) def populate_board(self): self.board[0][0] = BlackChessRook() self.board[0][1] = BlackChessKnight() self.board[0][2] = BlackChessBishop() self.board[0][3] = BlackChessQueen() self.board[0][4] = BlackChessKing() self.board[0][5] = BlackChessBishop() self.board[0][6] = BlackChessKnight() self.board[0][7] = BlackChessRook() self.board[7][0] = WhiteChessRook() self.board[7][1] = WhiteChessKnight() self.board[7][2] = WhiteChessBishop() self.board[7][3] = WhiteChessQueen() self.board[7][4] = WhiteChessKing() self.board[7][5] = WhiteChessBishop() self.board[7][6] = WhiteChessKnight() self.board[7][7] = WhiteChessRook() for column in range(8): self.board[1][column] = BlackChessPawn() self.board[6][column] = WhiteChessPawn() class Piece(str): __slots__ = () class BlackDraught(Piece): __slots__ = () def __new__(Class): return super().__new__(Class, "\N{black draughts man}") class WhiteDraught(Piece): __slots__ = () def __new__(Class): return super().__new__(Class, "\N{white draughts man}") class BlackChessKing(Piece): __slots__ = () def __new__(Class): return super().__new__(Class, "\N{black chess king}") class WhiteChessKing(Piece): __slots__ = () def __new__(Class): return super().__new__(Class, "\N{white chess king}") class BlackChessQueen(Piece): __slots__ = () def __new__(Class): return super().__new__(Class, "\N{black chess queen}") class WhiteChessQueen(Piece): __slots__ = () def __new__(Class): return super().__new__(Class, "\N{white chess queen}") class BlackChessRook(Piece): __slots__ = () def __new__(Class): return super().__new__(Class, "\N{black chess rook}") class WhiteChessRook(Piece): __slots__ = () def __new__(Class): return super().__new__(Class, "\N{white chess rook}") class BlackChessBishop(Piece): __slots__ = () def __new__(Class): return super().__new__(Class, "\N{black chess bishop}") class WhiteChessBishop(Piece): __slots__ = () def __new__(Class): return super().__new__(Class, "\N{white chess bishop}") class BlackChessKnight(Piece): __slots__ = () def __new__(Class): return super().__new__(Class, "\N{black chess knight}") class WhiteChessKnight(Piece): __slots__ = () def __new__(Class): return super().__new__(Class, "\N{white chess knight}") class BlackChessPawn(Piece): __slots__ = () def __new__(Class): return super().__new__(Class, "\N{black chess pawn}") class WhiteChessPawn(Piece): __slots__ = () def __new__(Class): return super().__new__(Class, "\N{white chess pawn}") if __name__ == "__main__": main()
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129
#!/usr/bin/env python3 # Copyright c 2012-13 Qtrac Ltd. All rights reserved. # This program or module is free software: you can redistribute it # and/or modify it under the terms of the GNU General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. It is provided for # educational purposes and is distributed in the hope that it will be # useful, but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. import io import itertools import os import sys import tempfile import unicodedata BLACK, WHITE = ("BLACK", "WHITE") def main(): checkers = CheckersBoard() print(checkers) chess = ChessBoard() print(chess) if sys.platform.startswith("win"): filename = os.path.join(tempfile.gettempdir(), "gameboard2.doc") with open(filename, "w", encoding="utf-8") as file: file.write(sys.stdout.getvalue()) print("wrote '{}'".format(filename), file=sys.__stdout__) if sys.platform.startswith("win"): def console(char, background): return char or " " sys.stdout = io.StringIO() else: def console(char, background): return "\x1B[{}m{}\x1B[0m".format( 43 if background == BLACK else 47, char or " ") class AbstractBoard: def __init__(self, rows, columns): self.board = [[None for _ in range(columns)] for _ in range(rows)] self.populate_board() def populate_board(self): raise NotImplementedError() def __str__(self): squares = [] for y, row in enumerate(self.board): for x, piece in enumerate(row): square = console(piece, BLACK if (y + x) % 2 else WHITE) squares.append(square) squares.append("\n") return "".join(squares) class CheckersBoard(AbstractBoard): def __init__(self): super().__init__(10, 10) def populate_board(self): for x in range(0, 9, 2): for y in range(4): column = x + ((y + 1) % 2) for row, color in ((y, "black"), (y + 6, "white")): self.board[row][column] = create_piece("draught", color) class ChessBoard(AbstractBoard): def __init__(self): super().__init__(8, 8) def populate_board(self): for row, color in ((0, "black"), (7, "white")): for columns, kind in (((0, 7), "rook"), ((1, 6), "knight"), ((2, 5), "bishop"), ((3,), "queen"), ((4,), "king")): for column in columns: self.board[row][column] = create_piece(kind, color) for column in range(8): for row, color in ((1, "black"), (6, "white")): self.board[row][column] = create_piece("pawn", color) def create_piece(kind, color): if kind == "draught": return eval("{}{}()".format(color.title(), kind.title())) return eval("{}Chess{}()".format(color.title(), kind.title())) # Using eval() is risky class Piece(str): __slots__ = () for code in itertools.chain((0x26C0, 0x26C2), range(0x2654, 0x2660)): char = chr(code) name = unicodedata.name(char).title().replace(" ", "") if name.endswith("sMan"): name = name[:-4] exec("""\ class {}(Piece): __slots__ = () def __new__(Class): return super().__new__(Class, "{}")""".format(name, char)) # Using exec() is risky if __name__ == "__main__": main()
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144
#!/usr/bin/env python3 # Copyright c 2012-13 Qtrac Ltd. All rights reserved. # This program or module is free software: you can redistribute it # and/or modify it under the terms of the GNU General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. It is provided for # educational purposes and is distributed in the hope that it will be # useful, but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. import io import itertools import os import sys import tempfile import unicodedata DRAUGHT, PAWN, ROOK, KNIGHT, BISHOP, KING, QUEEN = ("DRAUGHT", "PAWN", "ROOK", "KNIGHT", "BISHOP", "KING", "QUEEN") BLACK, WHITE = ("BLACK", "WHITE") def main(): checkers = CheckersBoard() print(checkers) chess = ChessBoard() print(chess) if sys.platform.startswith("win"): filename = os.path.join(tempfile.gettempdir(), "gameboard3.doc") with open(filename, "w", encoding="utf-8") as file: file.write(sys.stdout.getvalue()) print("wrote '{}'".format(filename), file=sys.__stdout__) if sys.platform.startswith("win"): def console(char, background): return char or " " sys.stdout = io.StringIO() else: def console(char, background): return "\x1B[{}m{}\x1B[0m".format( 43 if background == BLACK else 47, char or " ") class Piece(str): __slots__ = () def make_new_method(char): # Needed to create a fresh method each time def new(Class): # Can't use super() or super(Piece, Class) return Piece.__new__(Class, char) return new for code in itertools.chain((0x26C0, 0x26C2), range(0x2654, 0x2660)): char = chr(code) name = unicodedata.name(char).title().replace(" ", "") if name.endswith("sMan"): name = name[:-4] new = make_new_method(char) Class = type(name, (Piece,), dict(__slots__=(), __new__=new)) setattr(sys.modules[__name__], name, Class) # Can be done better! class AbstractBoard: __classForPiece = {(DRAUGHT, BLACK): BlackDraught, (PAWN, BLACK): BlackChessPawn, (ROOK, BLACK): BlackChessRook, (KNIGHT, BLACK): BlackChessKnight, (BISHOP, BLACK): BlackChessBishop, (KING, BLACK): BlackChessKing, (QUEEN, BLACK): BlackChessQueen, (DRAUGHT, WHITE): WhiteDraught, (PAWN, WHITE): WhiteChessPawn, (ROOK, WHITE): WhiteChessRook, (KNIGHT, WHITE): WhiteChessKnight, (BISHOP, WHITE): WhiteChessBishop, (KING, WHITE): WhiteChessKing, (QUEEN, WHITE): WhiteChessQueen} def __init__(self, rows, columns): self.board = [[None for _ in range(columns)] for _ in range(rows)] self.populate_board() def create_piece(self, kind, color): return AbstractBoard.__classForPiece[kind, color]() def populate_board(self): raise NotImplementedError() def __str__(self): squares = [] for y, row in enumerate(self.board): for x, piece in enumerate(row): square = console(piece, BLACK if (y + x) % 2 else WHITE) squares.append(square) squares.append("\n") return "".join(squares) class CheckersBoard(AbstractBoard): def __init__(self): super().__init__(10, 10) def populate_board(self): for x in range(0, 9, 2): for y in range(4): column = x + ((y + 1) % 2) for row, color in ((y, BLACK), (y + 6, WHITE)): self.board[row][column] = self.create_piece(DRAUGHT, color) class ChessBoard(AbstractBoard): def __init__(self): super().__init__(8, 8) def populate_board(self): for row, color in ((0, BLACK), (7, WHITE)): for columns, kind in (((0, 7), ROOK), ((1, 6), KNIGHT), ((2, 5), BISHOP), ((3,), QUEEN), ((4,), KING)): for column in columns: self.board[row][column] = self.create_piece(kind, color) for column in range(8): for row, color in ((1, BLACK), (6, WHITE)): self.board[row][column] = self.create_piece(PAWN, color) if __name__ == "__main__": main()
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132
#!/usr/bin/env python3 # Copyright c 2012-13 Qtrac Ltd. All rights reserved. # This program or module is free software: you can redistribute it # and/or modify it under the terms of the GNU General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. It is provided for # educational purposes and is distributed in the hope that it will be # useful, but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. import io import itertools import os import sys import tempfile import unicodedata DRAUGHT, PAWN, ROOK, KNIGHT, BISHOP, KING, QUEEN = ("DRAUGHT", "PAWN", "ROOK", "KNIGHT", "BISHOP", "KING", "QUEEN") BLACK, WHITE = ("BLACK", "WHITE") def main(): checkers = CheckersBoard() print(checkers) chess = ChessBoard() print(chess) if sys.platform.startswith("win"): filename = os.path.join(tempfile.gettempdir(), "gameboard4.doc") with open(filename, "w", encoding="utf-8") as file: file.write(sys.stdout.getvalue()) print("wrote '{}'".format(filename), file=sys.__stdout__) if sys.platform.startswith("win"): def console(char, background): return char or " " sys.stdout = io.StringIO() else: def console(char, background): return "\x1B[{}m{}\x1B[0m".format( 43 if background == BLACK else 47, char or " ") class AbstractBoard: def __init__(self, rows, columns): self.board = [[None for _ in range(columns)] for _ in range(rows)] self.populate_board() def populate_board(self): raise NotImplementedError() def __str__(self): squares = [] for y, row in enumerate(self.board): for x, piece in enumerate(row): square = console(piece, BLACK if (y + x) % 2 else WHITE) squares.append(square) squares.append("\n") return "".join(squares) class CheckersBoard(AbstractBoard): def __init__(self): self.populate_board() def populate_board(self): # Thanks to Doug Hellmann for the idea! def black(): return create_piece(DRAUGHT, BLACK) def white(): return create_piece(DRAUGHT, WHITE) rows = ((None, black()), (black(), None), (None, black()), (black(), None), # 4 black rows (None, None), (None, None), # 2 blank rows (None, white()), (white(), None), (None, white()), (white(), None)) # 4 white rows self.board = [list(itertools.islice( itertools.cycle(squares), 0, len(rows))) for squares in rows] class ChessBoard(AbstractBoard): def __init__(self): super().__init__(8, 8) def populate_board(self): for row, color in ((0, BLACK), (7, WHITE)): for columns, kind in (((0, 7), ROOK), ((1, 6), KNIGHT), ((2, 5), BISHOP), ((3,), QUEEN), ((4,), KING)): for column in columns: self.board[row][column] = create_piece(kind, color) for column in range(8): for row, color in ((1, BLACK), (6, WHITE)): self.board[row][column] = create_piece(PAWN, color) def create_piece(kind, color): color = "White" if color == WHITE else "Black" name = {DRAUGHT: "Draught", PAWN: "ChessPawn", ROOK: "ChessRook", KNIGHT: "ChessKnight", BISHOP: "ChessBishop", KING: "ChessKing", QUEEN: "ChessQueen"}[kind] return globals()[color + name]() class Piece(str): __slots__ = () for code in itertools.chain((0x26C0, 0x26C2), range(0x2654, 0x2660)): char = chr(code) name = unicodedata.name(char).title().replace(" ", "") if name.endswith("sMan"): name = name[:-4] new = (lambda char: lambda Class: Piece.__new__(Class, char))(char) new.__name__ = "__new__" Class = type(name, (Piece,), dict(__slots__=(), __new__=new)) globals()[name] = Class if __name__ == "__main__": main()