回答編集履歴

1

DRY

2016/10/26 13:44

投稿

退会済みユーザー
test CHANGED
@@ -47,3 +47,79 @@
47
47
  }
48
48
 
49
49
  ```
50
+
51
+
52
+
53
+ ###DRY (Do not Repeat Yourself) 追記
54
+
55
+ DRY、同じことを繰り返すなという原則。コードを削ります。
56
+
57
+
58
+
59
+ ```Java
60
+
61
+ abstract class TestClass {
62
+
63
+ protected String str;
64
+
65
+ protected int num;
66
+
67
+ public Object copy() {
68
+
69
+ return getInstance(this.str, this.num);
70
+
71
+ }
72
+
73
+ public static TestClass getInstance(String str, int num) {
74
+
75
+ TestClass instance = new TestClass() {};
76
+
77
+ instance.str = str;
78
+
79
+ instance.num = num;
80
+
81
+ return instance;
82
+
83
+ }
84
+
85
+ }
86
+
87
+ ```
88
+
89
+ ###でもね、抽象クラスが必要ですか?
90
+
91
+ インスタンスをつくらせたくなければ、コンストラクタをprivateにする方法もあります。自分しかインスタンスを作れない。
92
+
93
+
94
+
95
+ ```Java
96
+
97
+ public final class TestClass2 {
98
+
99
+ protected String str;
100
+
101
+ protected int num;
102
+
103
+ private TestClass2 () {}
104
+
105
+ public Object copy() {
106
+
107
+ return getInstance(this.str, this.num);
108
+
109
+ }
110
+
111
+ public static TestClass2 getInstance(String str, int num) {
112
+
113
+ TestClass2 instance = new TestClass2();
114
+
115
+ instance.str = str;
116
+
117
+ instance.num = num;
118
+
119
+ return instance;
120
+
121
+ }
122
+
123
+ }
124
+
125
+ ```