回答編集履歴

1

サンプルコード追加

2022/12/09 08:16

投稿

rim_yamamoto
rim_yamamoto

スコア22

test CHANGED
@@ -6,3 +6,80 @@
6
6
  ```
7
7
  クラス名は `product.__class__.__name__` で取れますので、この形でカウンターを持てば、Productクラスが増えてもMainを改変する必要はありません。
8
8
 
9
+ 実はPythonを書くのは初めてなのですが、ググりつつ辞書でカウンターを持つ形にコードを書き直してみました。
10
+
11
+ can110さんが言うように、上のコードにおいて'FirstProduct2'は存在しないので、実現したい意図と合っているのか少し疑問がありますが、そこはひとまず'FirstProduct1'にしています。
12
+
13
+ ```python
14
+ from abc import ABCMeta, abstractmethod
15
+ import pprint
16
+
17
+ class Main():
18
+ def __init__(self):
19
+ self.counter_dict = {}
20
+ self.obj_dict = {}
21
+
22
+ def create_obj(self, factory_type):
23
+ product = factory_type.create_product() # productのインスタンス作成
24
+ object_name = product.__class__.__name__ # productのクラス名
25
+ last_num = self.counter_dict.get(object_name, 0)
26
+ new_num = last_num + 1
27
+ product.num = new_num
28
+ self.counter_dict[object_name] = new_num
29
+ self.obj_dict[object_name + str(product.num)] = product
30
+
31
+ def print_name(self, product):
32
+ self.obj_dict[product].print_name()
33
+
34
+ class Factory(metaclass=ABCMeta): # factory
35
+ @abstractmethod
36
+ def create_product(self):
37
+ pass
38
+
39
+ class FirstFactory(Factory): # concrete factory
40
+ def create_product(self):
41
+ return FirstProduct()
42
+
43
+ class SecondFactory(Factory): # concrete factory
44
+ def create_product(self):
45
+ return SecondProduct()
46
+
47
+ class Product(metaclass=ABCMeta): #product
48
+ @abstractmethod
49
+ def print_name(self):
50
+ pass
51
+
52
+ class FirstProduct(Product): # concrete product
53
+ def __init__(self):
54
+ pass
55
+
56
+ def print_name(self):
57
+ print('First Product ' + str(self.num))
58
+
59
+ class SecondProduct(Product): # concrete product
60
+ def __init__(self):
61
+ pass
62
+
63
+ def print_name(self):
64
+ print('Second Product ' + str(self.num))
65
+
66
+ if __name__ == '__main__':
67
+ test_1 = Main() # 一つ目のMainオブジェクト
68
+ test_1.create_obj(FirstFactory())
69
+ test_1.create_obj(SecondFactory())
70
+
71
+ test_2 = Main() # 二つ目のMainオブジェクト
72
+ test_2.create_obj(FirstFactory())
73
+ test_2.create_obj(SecondFactory())
74
+
75
+ pprint.pprint(test_1.obj_dict)
76
+ print()
77
+ pprint.pprint(test_2.obj_dict)
78
+ print()
79
+
80
+ test_1.print_name('FirstProduct1')
81
+ test_1.print_name('SecondProduct1')
82
+ test_2.print_name('FirstProduct1')
83
+ test_2.print_name('SecondProduct1')
84
+ ```
85
+