Pot<T> constructor

Pot<T>(
  1. PotObjectFactory<T> factory, {
  2. PotDisposer<T>? disposer,
})

Creates a Pot that instantiates and caches an object of type T until it is discarded.

A Pot is a holder that keeps an object instance.

The factory provided to the constructor instantiates an object. It always works in a lazy manner; it does not create an object until it is first needed. The object is cached, so once it is created, a new one is not created unless the pot is reset or the factory is replaced.

The disposer is triggered when the object is disposed by methods such as reset and ReplaceablePot.replace.

final counterPot = Pot<Counter>(
  () => Counter(),
  disposer: (counter) => counter.dispose(),
);

void main() {
  // The factory has not been called yet at this point.
  ...

  // The factory creates a Counter object.
  final counter = counterPot();
  ...

  // The object is discarded and the disposer function is called.
  counterPot.reset();
}

instead of:

final counter = Counter();

It is possible to replace the factory and/or the object with ReplaceablePot.replace.

final counterPot = Pot.replaceable<User>(() => User.none());

void main() {
  counterPot.replace(() => User(id: 100));
}

or with replaceForTesting if the pot is not the one created by Pot.replaceable:

final counterPot = Pot(() => Counter());

void main() {
  Pot.forTesting = true;

  test('Some test', () {
    counterPot.replaceForTesting(() => MockCounter());
  });
}

It is easy to discard the object when it becomes no longer necessary.

final counter = counterPot();
final repository = repositoryPot();
...
Pot.resetAll();

The Pot class also provides the feature of scoping the range where particular objects exist.

// The index of the current scope changes from 0 to 1.
Pot.pushScope();

// A counter object is created in the scope 1.
counterPot.create();

// The object is discarded when the scope 1 is removed.
Pot.popScope();

Implementation

Pot(super.factory, {super.disposer});