File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 66@link: https://premaseem.wordpress.com/category/computers/design-patterns/
77*/
88public class Calculator {
9- static int num = 0 ;
10- public Calculator (){
9+ static int num = 0 ;
10+ private static Calculator instance = null ;
11+
12+ public static Calculator getInstance (){
13+ if (instance == null ){
14+ instance = new Calculator ();
15+ }
16+ return instance ;
17+ }
18+
19+ private Calculator () {
1120 num ++;
12- System .out .println (num + " wasting memory with new object" );
21+ System .out .println (num + " wasting memory with new object" );
1322 }
14- public Integer add (Integer sum , Integer number ){
23+
24+ public Integer add (Integer sum , Integer number ) {
1525 return sum + number ;
1626 }
1727}
Original file line number Diff line number Diff line change @@ -16,7 +16,7 @@ public static void main (String[] args) {
1616 private static Integer calculateSum () {
1717 Integer sum = 0 ;
1818 for (int i =0 ; i < 1000 ; i ++){
19- Calculator calc = new Calculator ();
19+ Calculator calc = Calculator . getInstance ();
2020 sum = calc .add (sum ,i );
2121 }
2222 return sum ;
You can’t perform that action at this time.
0 commit comments