본문 바로가기

flutter

singleton

1. 싱글톤 개념

객체의 인스턴스가 오직 하나만 생성되는 것, 즉 여러개의 생성자를 호출 하더라도 실제로 생성되는 인스턴스는 하나이다.

 

2. 싱글톤 형태

class Singleton {
  static final Singleton _instance = Singleton._internal();

  // _instance 값을 반환한다.
  // 값이 있으면 원래 값을 반환한다.
  factory Singleton() => _instance;

  Singleton._internal(){ // 클래스가 최초 생성될 때, 1회 발생
   // 초기화 코드
  }

}

 

3. 싱글톤 클래스, 일반 클래스 비교

class Singleton {

  late int count;

  static final Singleton _instance = Singleton._internal();

  // _instance 값을 반환한다.
  // 값이 있으면 원래 값을 반환한다.
  factory Singleton() => _instance;
  
  Singleton._internal(){ // 클래스가 최초 생성될 때, 1회 발생
   // 초기화 코드
    count = 0;
  }

}

class Normal {
  late int count;
  Normal(){
    count = 0;
  }
}

void main(List<String> arguments) {
  // 첫번째 일반 클래스 생성
  var n1 = Normal();
  // 두번째 일반 클래스 생성
  var n2 = Normal();
  // 첫번째 싱글톤 클래스 생성
  var s1 = Singleton();
  // 두번째 싱글톤 클래스 생성
  // 이미 생성되었기 때문에 이전에 생성된 인스턴스 넘겨줌
  // 초기화 코드 실행x
  var s2 = Singleton();

  // 클래스 생성후 count 값 출력
  print('normal one : ${n1.count}, two : ${n2.count}'); // normal one : 0, two : 0
  print('singleton one : ${s1.count}, two : ${s2.count}'); // singleton one : 0, two : 0

  n1.count++;
  n2.count++;
  s1.count++;
  s2.count++;

  // count 증가 후 출력
  print('normal one : ${n1.count}, two : ${n2.count}'); // normal one : 1, two : 1
  print('singleton one : ${s1.count}, two : ${s2.count}'); // singleton one : 2, two : 2

  print('normal same? : ${identical(n1, n2)}'); // normal same? : false
  print('singleton same? : ${identical(s1, s2)}'); // singleton same? : true

}

 

'flutter' 카테고리의 다른 글

context 없이 navigation 구현하기  (0) 2022.08.05
expandable fab  (0) 2022.06.15
flutter 해당 위젯 코드 쉽게 찾기  (0) 2022.05.31
BoxConstraints forces an infinite width  (0) 2022.05.26
IntrinsicWidth, UnconstrainedBox  (0) 2022.05.23