Search code examples
flutterdartservice

why do they instantiate the class and then throw that instance away?


I am trying to learn Dart language along with flutter. I have come across the following piece of code (taken from here: https://github.com/ppicas/flutter-android-background/blob/master/lib/counter_service.dart) :

import 'package:flutter/foundation.dart';

import 'counter.dart';

class CounterService {
  factory CounterService.instance() => _instance;

  CounterService._internal(); <<====================== Why is this line here ? What does it do?

  static final _instance = CounterService._internal();

  final _counter = Counter();

  ValueListenable<int> get count => _counter.count;

  void startCounting() {
    Stream.periodic(Duration(seconds: 1)).listen((_) {
      _counter.increment();
      print('Counter incremented: ${_counter.count.value}');
    });
  }
}

I could not figure out why the line of code is required there. I understand that we force returning a single instance of this class by implemented a private constructor and the only instance is created in the following line. So, why do we really have to have that line there?

I'd appreciate if a dart expert shed some light over it. Thanks


Solution

  • CounterService._internal();
    

    Is a private named constructor that creates an object and can be called only within the class (privacy).

    factory CounterService.instance() => _instance;
    

    Is a public named constructor that returns an object (CounterService object) and can be called outside the class.

    Now the question:

    How can the client of that class create an object?

    answer: he just calls CounterService.instance() which always return an object we have already instantiated from the internal private constructor. remember!

    static final _instance = CounterService._internal();
    

    _instance is a private object of the same type of its class, it's a composition

    Note: it's created using the private constructor, while the public constuctor always returns it. So, what's the purpose of the above code?

    it aims to return only one object of that class, it's a conformation to Singleton Design Pattern.

    Hope it helps you.