개발/Flutter

[Dart/Flutter] Factory 생성자에 대하여

라보떼 2023. 1. 10. 13:34

 

 

참고 -  https://dart.dev/guides/language/language-tour#factory-constructors 

Factory constructors

Use the factory keyword when implementing a constructor that doesn’t always create a new instance of
its class. For example, a factory constructor might return an instance from a cache, or it might return an instance of a subtype. 

 

Dart 가이드에서는 위와 같이 설명하고 있습니다.

항상 새로운 인스턴스를 생성하지 않는 생성자를 구현할때 factory 키워드를 사용하라고 합니다.

캐시에서 인스턴스를 반환하거나 그 하위 인스턴스를 반환할 수 있습니다.

싱글톤 패턴을 따르고 있습니다.

 

 

-예제코드-

class Logger {
  final String name;
  bool mute = false;

  static final Map<String, Logger> _cache = <String, Logger>{};

  factory Logger(String name) {
    return _cache.putIfAbsent(name, () => Logger._internal(name));
  }

  factory Logger.fromJson(Map<String, Object> json) {
    return Logger(json['name'].toString());
  }

  Logger._internal(this.name);

  void log(String msg) {
    if (!mute) print(msg);
  }
}

 

위 예제 에서는 _cache에 이전에 생성된 인스턴스가 있다면 기존의 인스턴스를 반환 하고 없다면

_internal 생성하여 반환 하도록 합니다.