Singleton Method
架構圖:
例子:
建立一個計數器(counter),只要有建立新的實例就會加一並且給一個編號(id),下列是它的類別圖。
例子:
Counter.java
public class Counter { // data field private static Counter counter =null ; private static int countNumber=0; private static int id =0 ; //constructor private Counter(){} ; //get only one instance public static Counter getInstance(){ if(counter==null) // 只會建立一次 { counter = new Counter() ; id = (int)(Math.random()*1000); //產生id countNumber++; } return counter ; } //return count number public int getCountNumber() { return countNumber ; } //return id public int getId() { return id; } } |
TestCounter.java
public class TestCounter { public static void main(String[] args) { Counter counter1 = Counter.getInstance() ; System.out.println("counter1 ID:"+counter1.getId()); System.out.println("counter1 CounterNumber:"+counter1.getCountNumber()); Counter counter2 = Counter.getInstance() ; System.out.println("counter2 ID:"+counter2.getId()); System.out.println("counter2 CounterNumber:"+counter2.getCountNumber()); } } |
counter1 ID:66
counter1 CounterNumber:1
counter2 ID:66
counter2 CounterNumber:1
留言
張貼留言